0

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

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 新手,所以不确定如何正确操作。我该如何实施?

4

1 回答 1

1

您的collection_select参数命名错误,并且您在控制器中的模型查找键入了错误的参数。请参阅此处的 Rails 文档

像这样的东西会起作用:

# 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
于 2013-06-03T16:20:23.253 回答