【问题标题】:belongs_to has_many assosiation helpbelongs_to has_many 关联帮助
【发布时间】:2010-09-06 16:20:05
【问题描述】:

我为模型类别和产品(均使用脚手架创建)创建了一个连接表。产品型号是这样的:

class Product < ActiveRecord::Base
  belongs_to :category 

  def category_id
    category.id if category
  end

  def category_id=(id)
    self.category = Category.find_by_id(id) unless id.blank?
  end
end

类别模型是这样的:

class Category < ActiveRecord::Base
  has_and_belongs_to_many :products
end

在 form.html.erb 中,我创建了一个包含所有类的 Dropbox,供用户选择:

<p>
      <label for="product_category_id">Category:</label><br />
      <%= f.collection_select :category_id, Category.find(:all), :id, :name, :prompt => "Select a Category" %>
</p>

然而,当我看产品展示时:

<p>
  <b>Category:</b>
  <%= @product.category_id %>
</p>

或产品列表(index.html.erb):

<td><%= product.category_id %></td>

没有类别。只是空白。我不明白。 category_id 方法或关联有问题吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    首先,您不需要显式的category_idcategory_id= 方法。 ActiveRecord 将为您处理 belongs_to 关联。

    其次,您是否想要 has_and_belongs_to_manyhas_many/belongs_to 关联之间似乎存在不匹配。如果你有一个连接表,那么你有前者,在这种情况下,关联的双方都应该用has_and_belongs_to_many 声明。如果您只是在 products 表上使用 category_id,那么您在 Category 上的关联的另一端应该是 has_many :products

    使用连接模型:

    class Categorization < ActiveRecord::Base
      belongs_to :category
      belongs_to :product
    end
    

    您将在 Product 类中定义:

    has_many :categorizations
    has_many :categories, :through => :categorizations
    

    然后,由于您的关联是“多”关联,因此您不会在产品上获得 .category 方法。但是,您确实获得了 categories 方法(加上更多方法 - 查看 has_many 文档)。如果您将collection_select 命名为category_ids,那么它应该可以按预期工作。您可能还想在选择中添加“多个”选项,以便选择多个类别。

    【讨论】:

    • 我尝试使用带有 product_id、category_id 属性的连接模型(分类模型)。分类belongs_to 类别和产品。通过 => 分类使用产品。我删除了 category_id 方法,但是当我这样做时,我在删除 category_id= 后收到错误消息“#<0x10415bfa8>&lt;&gt;
    【解决方案2】:

    您的关联显然不正确。正如所指出的,类别 has_many 产品。如果您想使用多对多关系,强烈建议您使用 has_many :through 关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      相关资源
      最近更新 更多