I have two models:
class Sentence < ActiveRecord::Base
attr_accessible :sentence_id, :authority_name #...
end
class Rule < ActiveRecord::Base
attr_accessible :description, :headline, :note, :sentence_id
end
I would like to know how to create belongs_to :sentence association on Rule which will behave like this pseudo-SQL code:
SELECT * FROM rules
INNER JOIN sentences ON rules.sentence_id = sentences.sentence_id;
Edit:
I would like get something like that
rule = Rule.find 797
# we all know how SQL query will look like...
rule.sentence
# => SELECT * FROM sentences
INNER JOIN rules ON rules.sentence_id = sentences.sentence_id
WHERE rules.id = 797
First off, is
sentence_idthe primary key of thesentencestable?If so then you just need to explicitly set that column as the primary key.
If
sentence_idis not the primary key, then you need to specify it as the “primary key” of the association. I didn’t get a chance to test the code, but it should be like this: