gpt4 book ai didi

ruby-on-rails - Rails - 覆盖 has_one 上的主键

转载 作者:行者123 更新时间:2023-12-03 16:14:11 25 4
gpt4 key购买 nike

我有以下关联,基本上我想通过用户 ID 而不是对象的 ID 进行链接。

class Tweet < ActiveRecord::Base
has_one :user_profile, :primary_key => 'userid', :foreign_key => 'twitter_userid'
class UserProfile < ActiveRecord::Base
belongs_to :tweet, :foreign_key => 'userid'

但是,以下规范失败,因为 twitter_userid 被重置为对象的 id
it "should have the user's twitter id set on their user profile" do
t = Tweet.new(:twitter_id => 1,
:status => 'Tester',
:userid => 'personA',
:user_profile => UserProfile.new(:twitter_userid => 'personA', :avatar => 'abc'))
t.save!
t.user_profile.twitter_userid.should == 'personA'
end

应该在他们的用户个人资料中设置用户的 Twitter id
expected: "personA",
got: 216 (using ==)

但是,以下确实通过了:

它“应该在保存后返回正确的头像”做
t = Tweet.new(:twitter_id => 1,
:status => '测试员',
:userid => 'personA',
:user_profile => UserProfile.new(:twitter_userid => 'personA', :avatar => 'abc'))
t.保存!

t.user_profile.avatar.should == 'abc'
结尾

如何强制它使用 userid 而不是 id?

谢谢

最佳答案

这里有两件事正在发生。我认为您已经切换了 :has_one 和 :belongs_to 声明。
:belongs_to出现在具有外键的模型中。:has_one出现在被引用的模型中(如果它只有一个,否则如果许多行 :belong_to 相同,它当然是一个 has_many )。更多信息阅读here .

首先,您需要指定(否决)模型的主键。在这里,我假设用户可以拥有多条推文而不是一条推文(否则替换为 :has_one )。

class UserProfile
set_primary_key :userid
has_many :tweets
end

那么你需要调整你的 :has_one宣言:
class Tweet
belongs_to :user_profile, :foreign_key => :userid
end

然后,其次,一旦您的关系设置正确,就无需同时分配 :user_profile:userid在创建时。要么你创建一个新的 UserProfile并且外键将自动正确,或者您分配一个 userid现有配置文件。

希望这可以帮助。

关于ruby-on-rails - Rails - 覆盖 has_one 上的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1406778/

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