繁体   English   中英

使用现有记录在Rails中向数据库添加新记录

[英]Using pre-existing records to add a new record to the database in rails

好的,您可以在下面看到我的模型和控制器。 我想要做的是,当用户添加新租约时,用户可以从数据库中已经存在的属性列表中选择property_id,也可以从文件中的租户列表中选择tenant_id 。 我对Rails还是比较陌生,真的不知道如何去做。 在我的控制器中,我放置了@property = Property.all @tenant = Tenant.all使它们可访问,但是我不知道如何以自己想要的方式利用它们。

租赁模式

class Lease < ActiveRecord::Base
  attr_accessible :lease_end, :lease_start, :property_id, :tenant_id
  belongs_to :tenant
  belongs_to :property
end

物业模型

class Property < ActiveRecord::Base
  attr_accessible :address_line_1, :city, :county, :image, :rent
  belongs_to :lease
end

租户模型

class Tenant < ActiveRecord::Base
  attr_accessible :email, :name, :phone
  belongs_to :lease 
end

用于添加新租赁和编辑租赁的租赁控制器方法

 def new
    @lease = Lease.new
    @property = Property.all
    @tenant = Tenant.all
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @lease }
    end
  end

  # GET /leases/1/edit
  def edit
    @lease = Lease.find(params[:id])
    @property = Property.all
    @tenant = Tenant.all
  end

编辑:下拉框工作,但选项不是我想要的。 我正在获得诸如#用于租户和#用于财产的选项。 我想获取租户名称和属性地址

_form文件代码已根据teresko的建议进行了更新

<%= form_for(@lease) do |f| %>
  <% if @lease.errors.any? %>
    <div id="error_explanation">
       <h2><%= pluralize(@lease.errors.count, "error") %> prohibited this lease from          
          being saved:</h2>
      <ul>
      <% @lease.errors.full_messages.each do |msg| %>
       <li><%= msg %></li>
     <% end %>
     </ul>
    </div>
 <% end %>

 <div class="field">
  <%= f.label :tenant_id %><br />
  <%= f.select :tenant, options_for_select(@tenants) %>
</div>
<div class="field">
  <%= f.label :property_id %><br />
  <%= f.select :property, options_for_select(@properties) %>
</div>
<div class="field">
  <%= f.label :lease_start %><br />
  <%= f.date_select :lease_start %>
</div>
<div class="field">
  <%= f.label :lease_end %><br />
  <%= f.date_select :lease_end %>
</div>
<div class="actions">
  <%= f.submit %>
</div>
<% end %>

首先提示:良好的做法是使用@properties当你有很多属性,而不是@property 同上@tenants

然后,您可以在新页面或编辑页面中进行设置:

<% form_for @lease do |f| %>
  <%= f.select :property, options_for_select(@properties) %>
  <%= f.select :tenant, options_for_select(@tenants) %>
<% end %>

下一个技巧是使用部分名为app/views/leases/_form.html.erb的文件设置newedit的渲染相同表单时的上一个表单。 然后,您的新视图和编辑视图将变为

<%= render :partial => 'form' %>

要显示特定的选项,您可以阅读options_for_select或options_from_collection_for_select文档

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select

<%= f.select :property, options_from_collection_for_select(@properties, 'id', 'name') %>

选择适合您情况的最佳方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM