gpt4 book ai didi

ruby-on-rails - Rails 不尊重 has_one 的模型关联

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:09 25 4
gpt4 key购买 nike

用户.rb

has_one :subscription, :inverse_of => :user

订阅.rb

has_one :credit_card, :inverse_of => :subscription

CreditCard.rb

belongs_to :user, :inverse_of => :credit_card
belongs_to :subscription, :inverse_of => :credit_card

信用卡 Controller 中:

def new
@credit_card = current_user.build_credit_card
end

def create
@credit_card = current_user.build_credit_card
end

if @credit_card.save
if @credit_card.save
format.html { redirect_to @credit_card, notice: 'Credit card was successfully created.' }
format.json { render action: 'show', status: :created, location: @credit_card }
else
format.html { render action: 'new' }
format.json { render json: @credit_card.errors, status: :unprocessable_entity }
end
end

但是,我仍然可以向我的用户模型添加多张信用卡。这怎么可能?如果我是正确的,只有 has_many 应该发出这样的行为? has_one 关联应该防止创建其他实体,据我所知,除了一个之外......

我尝试了所有变体,但仍然没有运气。

如有任何帮助,我们将不胜感激!

谢谢。

最佳答案

我从未使用过 has_one 关系,但 google 和堆栈溢出的强大功能帮助我理解了这一点。

Difference between has_one and belongs_to in Rails?

belongs_to 表示外键在这个类的表中。所以 belongs_to 只能进入持有外键的类。

has_one

表示另一个表中有一个外键引用了这个类。所以 has_one 只能进入由另一个表中的列引用的类。

也是在那篇文章中记住它的好方法:

I always think of it in terms of Toy Story. Andy 'has_one' Woody, Woody 'belongs_to' andy. Where is the foreign key? On Woody's sole.

这对于理解关系也很有用。

http://requiremind.com/differences-between-has-one-and-belongs-to-in-ruby-on-rails/

关于ruby-on-rails - Rails 不尊重 has_one 的模型关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20274469/

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