【问题标题】:How to change behaviour of Rails belongs_to如何改变 Rails 的belongs_to 行为
【发布时间】:2012-05-08 13:05:37
【问题描述】:

我有两个模型:

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

class Rule < ActiveRecord::Base
  attr_accessible :description, :headline, :note, :sentence_id
end

我想知道如何在 Rule 上创建 belongs_to :sentence 关联,其行为类似于以下伪 SQL 代码:

SELECT * FROM rules 
INNER JOIN sentences ON rules.sentence_id = sentences.sentence_id;

编辑:

我想要这样的东西

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

【问题讨论】:

  • 这里的问题是你想获取属于任何句子的所有规则(即,有些规则的 sentence_id 为空)?如果每个规则都属于一个句子,为什么句子模型的基本has_many :rules 和规则模型的belongs_to :sentence 不能完成你想要的?
  • 向问题添加了更多信息。 :)
  • 在我看来,基本的关联设置可以满足您的需求。这种方法缺少什么?
  • 这种方法缺少foreign_key的设置。当你做像belongs_to :sentence 这样的基本关联时,你仍然可以通过INNER JOIN sentences ON sentences.id = rules.sentence_id 加入而不是INNER JOIN sentences ON sentences.sentence_id = rules.sentence_id。我想最后一次加入。仔细读。 :P :D

标签: sql ruby-on-rails ruby-on-rails-3 associations belongs-to


【解决方案1】:

首先,sentence_idsentences 表的主键吗?

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

class Sentence < ActiveRecord::Base
  set_primary_key :sentence_id
end

class Rule < ActiveRecord::Base
  belongs_to :sentence
end

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

class Rule < ActiveRecord::Base
  belongs_to :sentence, :primary_key => :sentence_id
end

【讨论】:

  • 宾果游戏!效果很好。谢谢。 :D
  • 另外,set_primary_key 已被弃用。使用self.primary_key= 'sentence_id'
【解决方案2】:

在关系数据库理论中,外键总是转到主键。要获取活动记录以生成所需的 SQL,请设置主键。

class Sentence < ActiveRecord::Base
  set_primary_key :sentence_id

我认为这就是您想要的,但这里有一个替代方案。要进行自定义连接,请使用 joins() 方法并在 SQL 中提供所需的字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多