gpt4 book ai didi

sql - 如何改变 Rails belongs_to 的行为

转载 作者:行者123 更新时间:2023-12-02 05:44:16 24 4
gpt4 key购买 nike

我有两个模型:

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_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

关于sql - 如何改变 Rails belongs_to 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10499201/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com