用于获取关联对象的ActiveRecord关联方法

时间:2016-05-14 18:49:25

标签: ruby-on-rails activerecord

我有三种模式品牌,类别和国家在多对多关联中意味着每个品牌可能属于许多类别,每个类别可能有许多品牌,每个国家可能有许多类别和品牌我需要知道一种方式获取品牌所在的类别。

到目前为止,我有这个:

String newValue;
if (substringEnd != -1 ) {
    newValue = project.getProperties().getProperty(propertyName)
        .substring(substringStart, substringEnd);
} else {
    newValue = project.getProperties().getProperty(propertyName)
        .substring(substringStart);
}

创造了品牌和类别之间的关联,我被困住了。我不知道如何获取品牌所投入的类别。你能救我吗?

2 个答案:

答案 0 :(得分:1)

您必须在模型品牌类别之间使用 has_and_belongs_to_many 关联。

Rails指南在描述其工作原理方面做得非常出色。 http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

答案 1 :(得分:0)

创建HABTM关系。从创建新模型category开始,然后创建新迁移并将其命名为brands_categories,在新迁移中添加类别和品牌的引用。比如rails g migration brands_categories brand:references category:references。然后在您的brand_params中允许{:category_ids => []}, :categories_attributes => [:category]。要在您的品牌视图中添加类似此类的类别 <% Category.all.each do |cat| %>
  <div class="checkbox">
    <label>
    <%= check_box_tag "product[category_ids][]", cat.id, @product.categories.include?(cat) %>
<%= cat.category %>
   </label>
  </div>
 <% end %>