【问题标题】:access by active record query with join table record in has_many :through relation使用 has_many 中的连接表记录通过活动记录查询访问:通过关系
【发布时间】:2012-03-05 07:05:32
【问题描述】:

我有项目、地区和类别表,它们通过 item_region 和 item_category 表连接,它们的关系如下

class Item < ActiveRecord::Base    
  has_many :item_region    
  has_many :region, :through => :item_region    
  has_many :item_category    
  has_many :category, :through => :item_category    

class Region < ActiveRecord::Base    
  has_many :category    
  has_many :item, ::through => :item_category    

class ItemRegion < ActiveRecord::Base    
  belongs_to :item    
  belongs_to :region    
end    

class Category < ActiveRecord::Base    
  has_many :item, :through => :item_category    
  has_many :item_category    

class ItemCategory < ActiveRecord::Base    
  belongs_to :item    
  belongs_to :category    
end     

我想使用连接表从 region_id、category_id 和 item_id 中找到 item 和 category_name 和 region_name 的所有字段。

谢谢。

【问题讨论】:

  • 我希望我做对了(这就是为什么我将其发布为评论而不是答案)。如何获得所需的项目,然后从中获得所需的区域和类别。 item = Item.find(item_id,然后是 region = item.regions.where(:id =&gt; region_id)category = item.categories.where(:id =&gt; category_id)
  • 感谢您的回复,但是当我触发第二个查询 region = item.regions.where(:id => region_id) 时,它给出了错误,因为 item 是数组,所以它给了我“未定义方法区域”。
  • 嗯..对不起,但item 不是数组。 item = Item.find(item_id) 会给你一个itemItem 的对象。您可以通过Item.find(item_id).class 确认。错误“未定义的方法区域”是因为您没有正确设置关联的名称。例如,在 Item 模型中,它应该是 has_many :regions, :through =&gt; :item_regionshas_many :categories, :through =&gt; :item_categories。您需要执行item.region.where ... 但这不是一个好习惯,因为一个项目有很多区域。为 a 做 object.collections 很直观,有很多关联。
  • 要点是如果它的a有很多关联,你最好提供复数形式。请注意,Rails 仍然可以使用上述代码,但不遵循 Rails 的 CoC(约定优于配置)原则。如果您遵循约定,则不必进行大量配置。在api.rubyonrails.org/classes/ActiveRecord/Associations/… 处查看示例。同时,我会将其作为答案发布,以便您在(且仅当)它有助于解决您的问题时接受它。
  • 对不起,当我运行 item = Item.find(item_id).class 然后提高 item.inspect 它给了我 arry.I 的意思是说 item = Item.find(item_id) 给出数组items 然后我做 region = item.regions.where(:id => region_id) 这里 item 是从第一个查询中找到的数组....希望您理解并感谢您的回复。

标签: ruby-on-rails ruby-on-rails-3 activerecord join has-many-through


【解决方案1】:

我希望我做对了。如何获得所需的项目,然后从中获得所需的区域和类别。

item = Item.find(item_id)
region = item.regions.where(:id => region_id) 
category = item.categories.where(:id => category_id)

另一个建议,你最好为你的关联提供复数形式。为has_many 关联执行object.collections 很直观。请注意,Rails 仍然可以使用上述代码,但不遵循 Rails 的 CoC(约定优于配置)原则。如果您遵循约定,则不必进行大量配置。

在这里查看示例http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

就我个人而言,我更希望将我在 Item 模型中的关联设置为:

class Item < ActiveRecord::Base    
  has_many :item_regions    
  has_many :regions, :through => :item_regions    
  has_many :item_categories    
  has_many :categories, :through => :item_categories   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多