【发布时间】:2014-02-28 03:35:35
【问题描述】:
我在创建嵌套多态表单时遇到问题。我正在关注这个问题的解决方案:
Rails: has_many through with polymorphic association - will this work?
描述是:一个人可以有很多事件,每个事件可以有一个多态事件记录
以下是相关型号:
class Event < ActiveRecord::Base
belongs_to :person
belongs_to :eventable, :polymorphic => true
end
class Meal < ActiveRecord::Base
has_one :event, :as => eventable
end
class Workout < ActiveRecord::Base
has_one :event, :as => eventable
end
class Person < ActiveRecord::Base
has_many :events
has_many :meals, :through => :events, :source => :eventable,
:source_type => "Meal"
has_many :workouts, :through => :events, :source => :eventable,
:source_type => "Workout"
end
我的控制器如下所示:
def
@person = Person.new
@person.meals.new
@person.workouts.new
new
我的观点是这样的:
<%= form_for @person do |person| %>
<%= person.fields_for :meals, @person.meals.build do |meals| %>
<%= meals.text_field :food %>
<% end %>
<% end %>
我目前遇到的错误是:
未知属性:person_id
我认为多态关联阻碍了对象的创建,因为在创建人之前无法创建餐点?我是否正确设置了表格?谢谢!
【问题讨论】:
-
在
events表中是否有person_id列作为整数?另外,我认为您提供的控制器代码可能输入错误? -
我认为你不需要@person.meals.build
-
不,事件表中没有 person_id。哦,怎么打错了?
标签: ruby-on-rails