多态嵌套形式

时间:2014-02-04 08:58:13

标签: ruby-on-rails

我遇到创建嵌套多态形式的问题。我正在解决这个问题的解决方案:

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

我认为多态关联阻碍了对象的创建,因为在创建人之前不能创建饭菜?我是否正确设置了表单?谢谢!

1 个答案:

答案 0 :(得分:0)

您需要在person_id表中添加events属性(根据belongs_to关联)

还有一些其他问题需要解决:


<强>控制器

def new
    @person = Person.build
end

def create
    @person = Person.new(person_attributes)
    @person.save
end

private

def person_attributes
    params.require(:person).permit(:your, :attributes, events_attributes: [:eventable_type, :eventable_id, meal_attributes: [:params], workout_attributes: [:params]])
end

<强>模型

#app/models/person.rb
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"

    def self.build
        person = Person.new
        person.events.build.build_meal
        person.events.build.build_workout
    end

end

<强>视图

#app/views/people/new.html.erb
<%=  form_for @person do |person| %>
 <%= person.fields_for :events do |e| %>
   <%= e.fields_for :meal %>
       <%= e.text_field :food %>
   <% end %>
  <% end %>
<% end %>