Rails 4:has_many通过关联belongs_to多态关联

时间:2014-11-04 18:44:54

标签: ruby-on-rails-4 polymorphism nested-attributes has-many-through strong-parameters

我尝试在belongs_to多态关联上通过关联进行has_many。 为此,我创建了3个类:

意见.rb:

class Opinion < ActiveRecord::Base

  has_many :opinion_types
  has_many :name_applications, through: :opinion_types, source: :typeapplication, source_type: "NameApplication"

  accepts_nested_attributes_for :opinion_types
end

opinion_type.rb:

class OpinionType < ActiveRecord::Base

  belongs_to :opinion
  belongs_to :typeapplication, polymorphic: true

  accepts_nested_attributes_for :typeapplication
end

name_application.rb:

class NameApplication < ActiveRecord::Base

  has_one :opinion_type, as: :typeapplication
  has_one :opinion, through: :opinion_type
end

my OpinionsController:

class OpinionsController < ApplicationController

  def new
    @opinion = Opinion.new
    3.times do
      @opinion.name_applications << NameApplication.new
    end
  end

  def create
    @opinion = Opinion.new(params[opinions_params])
    @opinion.save

    redirect_to root_path
  end

private
  def opinions_params
    params.require(:opinion).permit(opinion_types_attributes: [name_applications: [:name]])
  end
end

我的new.html.erb

<%= form_for @opinion do |o| %>
  <%= o.fields_for :opinion_types do |ot| %>
    <%= ot.fields_for :name_applications do |na| %>
      <%= na.label :name, "Name" %><br />
      <%= na.text_field :name %><br />
    <% end %>
  <% end %>
  <%= o.submit %>
<% end %>

提交包含3个名字的表格后,我收到:

{"utf8"=>"✓",
 "authenticity_token"=>"blablabla",
 "opinion"=>{"opinion_types_attributes"=>{"0"=>{"name_applications"=>{"name"=>"name test"}},
 "1"=>{"name_applications"=>{"name"=>"name test 2"}},
 "2"=>{"name_applications"=>{"name"=>"name test 3"}}}},
 "commit"=>"Create Opinion"}

问题是:我有一个错误unknown attribute: name_applications

当我在Rails控制台中写道时:

a = Opinion.new
a.name_applications << NameApplication.new(name: :"test")
a.name_applications << NameApplication.new(name: :"test 2")
a.name_applications << NameApplication.new(name: :"test 3")
a.save

My Opinion模型和与我的Opinion模型关联的NameApplication模型正确保存。

我使用不同的帖子试图找到解决方案,但没有成功:

我不知道我的问题是否是:

  • my accepts_nested_attributes_for :typeapplication in my opinion_type model(因为它是多态关联)
  • 我的强大参数:params.require(:opinion).permit(opinion_types_attributes: [name_applications: [:name]])
  • 或其他

感谢您的帮助

更新: 我找到了解决方案,但不是很干净:

在我的OpinionsController中,我通过此

更改了我的创建操作
  def create
    @opinion = Opinion.new
    opinions_params[:opinion_types_attributes].each do |f, index|
      @opinion.name_applications << NameApplication.new(opinions_params[:opinion_types_attributes][:"#{index}"][:name_applications])
    end

    @opinion.save

    redirect_to root_path
  end

我仍然不明白为什么我不能只使用@opinion = Opinion.new(opinions_params)

对于任何可以帮助我理解的建议,我将不胜感激。

0 个答案:

没有答案