fields_for嵌套资源不起作用

时间:2014-05-10 05:06:17

标签: ruby-on-rails-4

我有以下关联:

class Campaign < ActiveRecord::Base
  has_many :events
end

class Event < ActiveRecord::Base
  belongs_to :campaign
  belongs_to :venue
  accepts_nested_attributes_for :venue
end

class Venue < ActiveRecord::Base
  has_many :events
end

我有以下表格:

<%= form_for([@campaign, @event]) do |f| %>
  <%= f.fields_for :venue do |v| %>
    <%= v.text_field :search %>
  <% end %>
<% end %>

fields_for区块中的任何内容都没有显示。但有趣的是,如果我将f.fields_for :venue更改为f.fields_for :venues,则会显示:search字段。

但是:场地不应该是复数:事件。即使在rails控制台Event.venues也不起作用

NoMethodError: undefined method `venues'

它还会生成错误的字段名称

这让我觉得我的模型关联得到了提升,但在审核了文档之后。它似乎并非如此。这是我的架构供参考:

  create_table "campaigns", force: true do |t|
    t.integer  "user_id"
    t.string   "title"
    t.text     "description"
    t.integer  "image_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "events", force: true do |t|
    t.integer  "campaign_id"
    t.datetime "start_date"
    t.datetime "end_date"
    t.integer  "venue_id"
    t.integer  "image_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "title"
    t.text     "description"
  end

  create_table "venues", force: true do |t|
    t.float    "latitude"
    t.float    "longitude"
    t.string   "address1"
    t.string   "address2"
    t.string   "city"
    t.string   "zip"
    t.string   "state"
    t.string   "country"
    t.string   "name"
    t.string   "gid"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

1 个答案:

答案 0 :(得分:1)

参见类似的SO帖子

1的 Does accepts_nested_attributes_for work with belongs_to?

2的 Getting fields_for and accepts_nested_attributes_for to work with a belongs_to relationship

正如其中一篇文章所述,实现目标的一种方法是将accepts_nested_attributes_for更改为has_many

class Campaign < ActiveRecord::Base
  has_many :events
  accepts_nested_attributes_for :events
end

class Event < ActiveRecord::Base
  belongs_to :campaign
  belongs_to :venue

end

class Venue < ActiveRecord::Base
  has_many :events
  accepts_nested_attributes_for :events
end

如果不是,您可能希望在调用venue之前在控制器中为events @event.build_venue构建fields_for

希望它有所帮助!