嵌套表单has_many

时间:2013-01-05 20:40:30

标签: ruby-on-rails ruby-on-rails-3 nested-forms

我不确定如何使用嵌套表单正确创建rails表单。我已经遵循了许多教程,但变得更加困惑的是它应该是什么,奇异的多项式,控制器...这里我的模型

模型/ event.rb

  attr_accessible :description :title, :tag_ids, :locations_attributes
  has_many :location
  accepts_nested_attributes_for :location, :allow_destroy => true

模型/ location.rb

  attr_accessible :address, :customer_id, :event_id, :latitude, :longitude
  belongs_to :customer
  belongs_to :event

controller.rb

  def new
    @event = Event.new
    ...
  def create
    @event = Event.new(params[:event])
    ...

查看form.html.erb

<%= form_for(@event) do |f| %>
  <%= f.fields_for :locations do |e| %>
    <%= e.text_field :longitude %>
    <%= e.text_field :latitude %>
  <% end %>
  ...
<% end %>

错误

Can't mass-assign protected attributes: locations

params发送

 "locations"=>{"longitude"=>"45.6666",
 "latitude"=>"47.44444665"},

我的关系是错误的,因为fields_for不支持它,或者我的控制器不正确,或者rails不是一种优秀的语言,或者我不再理解它。

2 个答案:

答案 0 :(得分:2)

你几乎就在那里......

event.rb - locations NOT location

attr_accessible :description :title, :tag_ids, :locations_attributes
has_many :locations
accepts_nested_attributes_for :locations, :allow_destroy => true

应该这样做我想

修改

正如Valery Kvon所说,你需要添加

@event.locations.build

到您的控制器

答案 1 :(得分:1)

爱德华的回答+

def new
  @event = Event.new
  @event.locations.build
end