【问题标题】:Rails 3 - model issue, foreign keyRails 3 - 模型问题,外键
【发布时间】:2011-11-02 11:24:55
【问题描述】:

我有两个模型,Like 和 Photo。

class Like < ActiveRecord::Base
  belongs_to :photo, :class_name => "DataLike", :foreign_key => "photo_id"
end

class Photo < ActiveRecord::Base  
  has_many :likes
end

现在我尝试执行这个查询:

query = Like.select(:photo_id).joins(:photo).count

但我仍然收到此错误:

未初始化的常量 Like::DataLike

谁能帮帮我,拜托,我做错了什么?

非常感谢

【问题讨论】:

    标签: ruby-on-rails-3 activerecord model foreign-keys foreign-key-relationship


    【解决方案1】:

    你似乎没有DataLike 模型,我最好的猜测是你想链接到Photo 模型:

    class Like < ActiveRecord::Base
      belongs_to :photo, :foreign_key => "photo_id"
    end
    
    class Photo < ActiveRecord::Base  
      has_many :likes
    end
    

    如果您省略 :class_name 选项,则会推断出 Photo 模型。用于指定链接模型的类,以防与关联名称不同。

    【讨论】:

      猜你喜欢
      • 2011-04-13
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      相关资源
      最近更新 更多