如何改变Rails belongs_to的行为

not*_*ere 2 sql ruby-on-rails associations belongs-to ruby-on-rails-3

我有两个型号:

class Sentence < ActiveRecord::Base
  attr_accessible :sentence_id, :authority_name #...
end

class Rule < ActiveRecord::Base
  attr_accessible :description, :headline, :note, :sentence_id
end
Run Code Online (Sandbox Code Playgroud)

我想知道如何创建belongs_to :sentenceRule此伪SQL代码类似的关联:

SELECT * FROM rules 
INNER JOIN sentences ON rules.sentence_id = sentences.sentence_id;
Run Code Online (Sandbox Code Playgroud)

编辑:

我想得到类似的东西

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
Run Code Online (Sandbox Code Playgroud)

Wiz*_*Ogz 5

首先,是表sentence_id的主键sentences吗?

如果是这样,那么您只需要将该列显式设置为主键.

class Sentence < ActiveRecord::Base
  set_primary_key :sentence_id
end

class Rule < ActiveRecord::Base
  belongs_to :sentence
end
Run Code Online (Sandbox Code Playgroud)

如果sentence_id不是主键,则需要将其指定为关联的"主键".我没有机会测试代码,但它应该是这样的:

class Rule < ActiveRecord::Base
  belongs_to :sentence, :primary_key => :sentence_id
end
Run Code Online (Sandbox Code Playgroud)