【问题标题】:has_many through associations with key other than idhas_many 通过与 id 以外的键的关联
【发布时间】:2013-07-25 04:16:56
【问题描述】:

我需要创建一个 has_many :through 关联,其中一个外键不是模型 ID,而是名称

class User < ActiveRecord::Base  
  has_many :ownerships
  has_many :articles, :through => :ownerships
end

class Article < ActiveRecord::Base  
  has_many :ownerships
  has_many :users, :through => :ownerships
end

class Ownership < ActiveRecord::Base
  belongs_to :user
  belongs_to :article
end




create_table "ownerships", :force => true do |t|
    t.integer  "user_id"
    t.string   "article_code"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

我尝试将 foreign_keys 分配给关联,但没有运气。

有没有办法使用内置的 RoR 关联来实现我的目标?

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:
    class Article < ActiveRecord::Base  
      has_many :ownerships, :foreign_key => :article_code, :primary_key => "code"
      has_many :users, :through => :ownerships
    end
    
    class Ownership < ActiveRecord::Base
      belongs_to :user
      belongs_to :article, :foreign_key => :article_code, :primary_key => "code"
    
    end
    

    【讨论】:

    • 感谢您的回复。这样,一切似乎都正常,我可以通过 from 保存相关文章并检索相关文章,但“article_code”列包含文章 ID。
    猜你喜欢
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 2012-07-09
    • 1970-01-01
    相关资源
    最近更新 更多