2010-09-05 73 views
0

我为此目的创建了一个连接表。下面的代码:产品 - 分类关联。 (编辑)belongs_to,has_and_belongs_to_many?

class CreateCategoriesProductsJoin < ActiveRecord::Migration 
    def self.up 
    create_table 'categories_products', :id => false do |t| 
     t.column 'category_id', :integer 
     t.column 'product_id', :integer 
    end 
    end 

    def self.down 
    drop_table 'categories_products' 
    end 
end 

产品型号:

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
    attr_accessor :new_category_name 
    before_save :create_category_from_name 

    def create_category_from_name 
    create_category(:name => new_category_name) unless new_category_name.blank? 
    end 
end 

和类别型号:

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :products 
end 

到目前为止好。问题在于form.html.erb。 代码在这里:

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

我尝试加载类别的选择框,但我得到一个消息“未定义的方法`CATEGORY_ID”为#”。

我不明白为什么?我也尝试过has_many:通过但发生了同样的事情。

我应该能够以这种方式绘制类别,因为它们是关联的,但我不是。有任何想法吗?

我试过从railscast.com的screancast,但没有运气。你有没有想到一个完整的教程/产品类别,子类别关联的例子?我还没有找到一个下降(除了railscast,但不适合我)。

非常感谢您的时间,并感谢您花时间回复的麻烦(如果您确实如此)。

编辑:我发现它是在产品模型中的问题。这里是修复:

class Product < ActiveRecord::Base 
    belongs_to :category 

    def category_name 
    category.name if category 
    end 

    def category_name=(name) 
    self.category = Category.find_by_name(name) unless name.blank? 
    end 

end 

编辑2:我也有类别的另一个问题。

类别名称未出现在视图中。我称之为category_name函数,但我没有得到任何回报。像这样(show.html.erb):

<p> 
     <label for="product_category_id">Category:</label><br /> 
     <%= f.collection_select :category_name, Category.find(:all), :id, :name, :prompt => "Select a Category" %> 
     or create one: 
     <%= f.text_field :new_category_name %> 
</p> 

或(show.html.erb):

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

我试图改变has_and_belongs_to_many :categories至少我回来了 “分类” 为这个名字很奇怪......因为我有4个类别。

A产品只属于一个类别。 PS:再一次,谢谢你的时间。

回答

0
<%= f.collection_select :category_id ... %> 

即线正在寻找.category_id形式对象,它具有依赖性的形式是为(我假设它是一个产品对象)创建的对象上访问器上。产品对象具有has_and_belongs_to_many与类别关系的属性,但它不是单个类别ID。可用的方法列于here。我不能肯定,因为我从来没有使用has_and_belongs_to_many,但我想你会想

<%= f.collection_select :categories_singular_ids ... %> 

的collection_select将需要多选,所以对你的HTML,你会想在:multiple => true最后的选项散列。

+0

不说也不行。 – storedope 2010-09-05 21:52:09

0

尝试以下操作:

<%= f.select :category_ids, Category.pluck(:name, :id), { prompt: "Select a Category" }, multiple: true %> 

不要忘记允许category_ids,即: params.require(:product).permit(category_ids: [])