如何创建和保存具有has_many / belongs_to关联的模型

时间:2013-06-03 15:38:50

标签: ruby-on-rails database ruby-on-rails-3

我正在构建一个应用程序,我有一个像这样的模型

class Region < ActiveRecord::Base
  attr_accessible :region_name
  has_many :districts, dependent: :destroy
end

class District < ActiveRecord::Base
  attr_accessible :district_name
  belongs_to :region
  has_many :counties, dependent: :destroy
  validates :region_id, presence: true
 end

我一直在使用db / seed这样添加区域和区域

region1 = Region.find_or_create_by_region_name :region_name => 'Central'
district1 = region1.districts.create(district_name: 'Kampala')

现在这很麻烦,你可以想象所以我想创建一个简单的表格,我可以添加一个区域并使用选择菜单将其与正确的区域相关联。

所以这是我的区\ new.html.erb视图

<div class="region">
<%= form_for (@district) do |f| %>
<%= f.label :region %>
<%= f.collection_select :region, Region.all,:id, :region_name, :prompt => "-- Select       Region --" %>
<%= f.label :district %>
<%= f.text_field :district_name %>
<%= f.submit "Add District", class: "btn btn-large btn-primary" %>
<%end%>
</div>

这是我的区控制器创建方法

def create
  @region = Region.find_by_region_name(params[:region_name])
  @district = @region.districts.create!(params[:district])
  if @district.save
    redirect_to :districts_path, :notice => "District added"
    else
      render :new
    end
end

这正如您所期望的那样无效。我是rails的新手,所以我不确定如何正确地做到这一点。我该如何实现呢?

1 个答案:

答案 0 :(得分:1)

您的collection_select参数名称错误,您控制器中的模型查找键入了错误的参数。请参阅Rails documentation here

这样的事情会起作用:

# app/views/districts/new.html.erb    
<%= collection_select :region, :region_id, Region.all, :id, :region_name, :prompt => "-- Select       Region --" %> # notice that `collection_select` is not being passed to `f`

# app/controllers/districts_controller.rb
def create
    @region = Region.find(params[:district][:region_id])
    ...
end