I need to create an has_many :through association where one foreign key is not the model id but the name

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

I have tried assigning foreign_keys to the associations but without luck.

Is there a way to achieve my goal using the built-in RoR associations?

没有正确的解决方案

其他提示

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top