Ruby on Rails:选择嵌套模型的所有记录的简单方法? [英] Ruby on Rails: Simple way to select all records of a nested model?
问题描述
很好奇,我花了很多时间来尝试在嵌套模型中获取所有记录的数组.我只想确保没有更好的方法.
Just curious, I spent an embarrassing amount of time trying to get an array of all the records in a nested model. I just want to make sure there is not a better way.
这是设置:
我有三个相互嵌套的模型(设施>>标签>>检查),为route.rb生成了这样的代码:
I have three models that are nested under each other (Facilities >> Tags >> Inspections), producing code like this for routes.rb:
map.resources :facilities do |facilities|
facilities.resources :tags, :has_many => :inspections
end
我想对设施进行所有检查,这就是我的代码最终的结果:
I wanted to get all of the inspections for a facility and here is what my code ended up being:
def facility_inspections
@facility = Facility.find(params[:facility_id])
@inspections = []
@facility.tags.each do |tag|
tag.inspections.each do |inspection|
@inspections << inspection
end
end
end
它有效,但这是执行此操作的最佳方法-我认为这很麻烦.
It works but is this the best way to do this - I think it's cumbersome.
推荐答案
您可以使用has_many :through
关联.在您的模型中:
You can use has_many :through
association. In your models:
# Facility model
has_many :tags
has_many :inspections, :through => :tags
# Tag model
belongs_to :facility
has_many :inspections
您可以得到所有这样的检查:
And you can get all inspections like this:
@inspections = Facility.find(params[:facility_id]).inspections
但是如果您在Facility和Tag之间具有HABTM关系,它将变得更加复杂,并且您将不得不手动编写一些sql,如下所示:
But if you have HABTM relation between Facility and Tag it will be more complicated and you would have to write some sql manualy, like this:
@inspections = Inspection.all(:joins => "INNER JOIN tags ON tags.id = inspections.tag_id INNER JOIN facilities_tags ON tags.id = facilities_tags.tag_id", :conditions => ["facilities_tags.facility_id = ?", params[:facility_id] )
当然,以上代码取决于您的表结构.如果您将显示它,那么给出正确答案将更容易:).希望对您有帮助!
Of course above code depends on your table structure. If you will show it, then it would be easier to give correct answer :). Hope it helps!
这篇关于Ruby on Rails:选择嵌套模型的所有记录的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!