【问题标题】:Can I have a has-many-through association via a parent model?我可以通过父模型进行多次关联吗?
【发布时间】:2016-02-22 17:31:17
【问题描述】:

我构建了一个表单,让用户可以在我们的应用上设置店面。它工作正常。

我现在正在尝试添加将问题与产品相关联的功能。并非每个问题都适用于每种产品。例如,如果一家店面正在销售一件 T 恤,则适用的问题可能是“您的尺码是多少?”。

这是我的模型的基本图:

以下是我的模型类中的相关行:

class Organization < ActiveRecord::Base
  has_one :storefront
  has_many :questions
end

class Storefront < ActiveRecord::Base
  belongs_to :organization
  has_many :questions, through: :organizations
  has_many :products, class_name: Product::Base, dependent: :destroy
end

class Product::Base < ActiveRecord::Base
  belongs_to :storefront
  has_many :product_question_applicabilities
end

class ProductQuestionApplicability < ActiveRecord::Base
  belongs_to :product,  inverse_of: :product_question_applicabilities
  belongs_to :question, inverse_of: :product_question_applicabilities
end

class Question < ActiveRecord::Base
  belongs_to :organization
  has_many :answers
end

我在设置表单以接受新问题模型的属性时遇到问题。

这是我的表单的样子(精简到相关行):

<%= form_for @storefront, url: create_or_edit_storefront_path(@storefront) do |f| %>

  <%= f.fields_for :questions do |ff| %>
    <%= render 'question_fields', f: ff %>
  <% end %>
  <%= link_to_add_association 'add question', f, :questions, :class => "add-question new-thing flat-link" %>

<% end %>

这给了我一个错误“ActiveRecord::HasManyThroughAssociationNotFoundError in Storefronts#edit,找不到关联:模型店面中的组织”

我是否正确设置了模型以实现这一目标?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord associations


    【解决方案1】:

    您需要将accepts_nested_attributes_for 添加到您的模型中

    尝试改变

    class Storefront < ActiveRecord::Base
      belongs_to :organization
      has_many :questions, through: :organizations
      has_many :products, class_name: Product::Base, dependent: :destroy
    end
    

        class Storefront < ActiveRecord::Base
          belongs_to :organization
          has_many :questions, through: :organizations
          has_many :products, class_name: Product::Base, dependent: :destroy
        accepts_nested_attributes_for :questions
       end
    

    【讨论】:

      猜你喜欢
      • 2018-08-29
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 2019-11-14
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多