优雅选择从的has_many属性:通过加入模型的Rails [英] Elegantly selecting attributes from has_many :through join models in Rails
问题描述
我不知道什么的has_many选择从加入模型属性的最简单/最优雅的方式:通过协会为
I'm wondering what the easiest/most elegant way of selecting attributes from join models in has_many :through associations is.
假设我们有一个项目,产品目录,并用以下Item类CatalogItems:
Lets say we have Items, Catalogs, and CatalogItems with the following Item class:
class Item < ActiveRecord::Base
has_many :catalog_items
has_many :catalogs, :through => :catalog_items
end
此外,可以说,该CatalogueItems具有位置属性和只有一个任何目录和任何项之间CatalogueItem。
Additionally, lets say that CatalogueItems has a position attribute and that there is only one CatalogueItem between any catalog and any item.
检索位置属性最明显的但稍微令人沮丧的方法是:
The most obvious but slightly frustrating way to retrieve the position attribute is:
@item = Item.find(4)
@catalog = @item.catalogs.first
@cat_item = @item.catalog_items.first(:conditions => {:catalog_id => @catalog.id})
position = @cat_item.position
这是烦人,因为我们似乎应该能够做到@ item.catalogs.first.position因为我们已经完全确定我们需要哪个位置是:对应于第一@项目的目录之一。
This is annoying because it seems that we should be able to do @item.catalogs.first.position since we have completely specified which position we want: the one that corresponds to the first of @item's catalogs.
我发现让这个唯一的办法是:
The only way I've found to get this is:
class Item < ActiveRecord::Base
has_many :catalog_items
has_many :catalogs, :through => :catalog_items, :select => "catalogue_items.position, catalogs.*"
end
现在我能做的Item.catalogs.first.position。然而,这似乎是一个黑客位的 - 我增加额外的属性到目录实例。它也开辟了试图利用在我填充一个Catalog.find或用@ item.catalogs @catalogs两种不同情况的视图的可能性。在一种情况下,该位置将在那里,并在另一方面,它也不会。
Now I can do Item.catalogs.first.position. However, this seems like a bit of a hack - I'm adding an extra attribute onto a Catalog instance. It also opens up the possibility of trying to use a view in two different situations where I populate @catalogs with a Catalog.find or with a @item.catalogs. In one case, the position will be there, and in the other, it won't.
有没有人有一个很好的解决这个?
Does anyone have a good solution to this?
感谢。
推荐答案
您可以做这样的事情:
# which is basically same as your "frustrating way" of doing it
@item.catalog_items.find_by_catalogue_id(@item.catalogs.first.id).position
或者你也可以在项目模型的实例方法,把它包装成:
Or you can wrap it into in an instance method of the Item model:
def position_in_first_catalogue
self.catalog_items.find_by_catalogue_id(self.catalogs.first.id).position
end
然后就调用它是这样的:
and then just call it like this:
@item.position_in_first_catalogue
这篇关于优雅选择从的has_many属性:通过加入模型的Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!