views:

31

answers:

2

I have an association:
an author has many books; and a book has many authors;
I need to use :through option(through a table named 'relations',has two column named 'left_id' (used as author_id) and 'right_id' (used ad book_id);


class Relation < ActiveRecord::Base
  belongs_to :books
  belongs_to :authors
end

class Author < ActiveRecord::Base
  has_many :relations, :foreign_key => 'left_id'
  has_many :books, :through => :relations
end

In the console:


> author = Author.new
> author.books 
#  => Error: no such column: relations.book_id

So, how could I specific the 'book_id' to 'right_id'?(Is there some option like 'foreign_key'?)

A: 

I don't know about foreign_id and can't find anything on google. How about this?

has_many :relations, :local_key => 'left_id', :foreign_key => 'right_id'
mark
ArgumentError: Unknown key(s): local_key
Croplio
Sorry, yes, it's foreign_key
Croplio
A: 

You should use a foreign_key also in the Relation model, so the belongs_to has also foreign_key. More specifically this is what you need:

class Relation < ActiveRecord::Base
  belongs_to :book, :foreign_key => :left_id
  belongs_to :author, :foreign_key => :right_id
end

and the other models should be:

class Book < ActiveRecord::Base
  has_many :relations, :foreign_key => :left_id
  has_many :authors, :through => :relations
end


class Author < ActiveRecord::Base
  has_many :relations, :foreign_key => :right_id
  has_many :books, :through => :relations
end
JohnDel
I'd hazard to add that it's probably a good practice to make the name of your through model a meaningful description of the relationship.Given the relationship books and authors, Authorship would make sense, though you can chase you tail forever trying to come up with something truly semantically meaningful. It's useful to use a semi-descriptive name so that when maintaining code later the name gives you a context automatically for evaluating what it's responsible for.
darkliquid