【问题标题】:Link two models through middlemodel at Rails 3.x在 Rails 3.x 中通过中间模型链接两个模型
【发布时间】:2011-07-18 19:57:18
【问题描述】:

我想我还不知道正确的术语,因此很难找到正确的答案。

所以,我创建了一个带有 Exhibit 和 Category 的引擎。我创建了第三个模型分类,以便将展览分配给多个类别。这只有exhibition_id 和category_id。

我想做的是为每个类别创建一个页面,因此我将一个展览分配给新闻类别,将其显示在“新闻”页面中,何时将其分配给照片类别以将其显示在“照片”中page 等。我猜这是一个路由配置,但我还没有到那里(但是,如果它确实是一个路由配置,请告诉我)

我的问题是如何仅从一个控制器中检索来自不同模型的字段。我有什么:

class Categorization < ActiveRecord::Base
  belongs_to :exhibit
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :exhibits, :through => :categorizations
  acts_as_indexed :fields => [:title]
  validates :title, :presence => true, :uniqueness => true 
end

class Exhibit < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations, :source => :category
  acts_as_indexed :fields => [:title, :bulb]
  validates :title, :presence => true, :uniqueness => true
  belongs_to :foto, :class_name => 'Image'
end

如何检索属于:category =&gt;"News"Exhibit:foto

我尝试在Categorization 模型中添加scope :news, where(['category_id="1"']),我可以检索Categorization.news,但是如何将Categorization.exhibit_id 与该展览的照片连接起来(我猜这是Exhibit.foto)?

我不知道从哪里开始......

谢谢大家...

石油

【问题讨论】:

    标签: ruby-on-rails-3 activerecord refinerycms active-relation


    【解决方案1】:

    我会在控制台中试试这个:

    Categorization.news.first.exhibit.foto    
    

    看看这是否不会为您提供所需的 Image 对象。问题是新闻有几种可能的表现。

    【讨论】:

    • ...没错!我如何获得all 而不是first?无论如何,非常感谢,上面的查询是一个魅力!
    • 我试过这个:Categorization.news.each do |t| t.exhibit.foto end ...但它返回了Categorization.news
    • 这很奇怪。我完全复制了您的代码 - 我得到了 Image 对象。可能是您正在查看控制台输出,它显示了 Categorization.news 数组(在控制台中应该如此)。关键是在每个周期中,您都没有对 t.exhibit.foto 做任何事情。可能你的意思是Categorization.new.each do |t| puts t.exhibit.foto.url end 还是什么?我不知道你的 Image 模型是否有任何属性,我认为 url 应该是它的一部分,但使用你在那里的东西。它应该为您提供 Image 属性。
    • 刚下班回来测试了一下。你是对的,我尝试不使用.url 方法。非常感谢您的帮助非常有启发性!!!
    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多