0

I have a type model that has_many :products and a product model that has_one :type.

The dynamic methods are working okay, but only if .product is called on an object that contains only one instance of type.

controller:

def index
    @all = Type.all
    @one = Type.find_by_id(2)
end 

view:

<%= debug @one.products %> #=> Hash of products with the type_id of 2

So far so good, but then:

<%= debug @all.products %>

results in a no 'products method defined' error. I think I sort of know why. @all contains multiple ids, and rails can't work out that I want all of the product entries that contain those multiple foreign keys. It seems it can only manage querying automatically for one foreign key.

Should this be a many to many relationship? That doesn't make sense, because every product really does only have one type. But how can I query for multiple types concisely?

What is want to achieve is have all of the product entries on one page, product entries that belong to all of the type entries.

screen cap of the different data structures

4

2 回答 2

1

这里有2点:

  1. 使用belongs_to 而不是has_one。has_one 和 belongs_to 代表一对一的关系;has_many 和 belongs_to 代表一对多关系。
  2. :products 是@type 的实例方法,但 Type.all 就像一个数组。
于 2013-09-27T14:47:41.523 回答
1

@all = Type.all返回一个没有.products方法的 ActiveRecord::Relation。 @one = Type.find_by_id(2)返回一个实际对象,该对象具有.products,正如您使用 定义的那样has_many :products

如果你想拥有所有类型的所有产品,要么Product.where('type_id = ?', 2')按照 Bachan Smruty 所说的去做,要么做(不太受欢迎)@all.collect(&:products)。在后者中,您希望使用Type.includes(:products).all. 但据我所知,这是最慢的方式,因为您首先重组了一组对象,您可能不需要收集另一组对象。

于 2013-09-27T14:20:01.893 回答