2013-11-28 156 views
2

User.rbRails不尊重模型关联的HAS_ONE

has_one :subscription, :inverse_of => :user 

Subscription.rb

has_one :credit_card, :inverse_of => :subscription 

CreditCard.rb

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

信用卡控制器

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协会应该防止创建额外的实体,除了一个据我所知..

我试过所有的变化,但仍然没有运气。

任何帮助将不胜感激!

谢谢。

+0

你是什么意思,它的作品?什么代码可以添加多张卡片,以及什么让你认为它不应该在工作? – dpassage

+0

用户拥有一张信用卡,但是任何给定的用户仍然可以创建多张卡片?简而言之,当它是has_one关联时,它的行为就好像是has_many。我希望这可以澄清我的问题。 – dsignr

回答

2

我从来没有使用has_one关系,但谷歌和堆栈溢出的力量帮助我理解了这一点。

Difference between has_one and belongs_to in Rails?

belongs_to意味着外键是表中的这个类。所以belongs_to只能进入持有外键的类。

has_one 

意味着在另一个表中有一个引用这个类的外键。所以has_one只能进入另一个表中的列所引用的类。

也是一个很好的方式来记住它在该职位:

我一直认为它在玩具总动员方面。 Andy'has_one'伍迪, 伍迪'属于'安迪。外键在哪里?在伍迪的鞋底上。

此外,这对理解关系很有用。

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

+0

谢谢,这是相当丰富的:) – dsignr

+1

对于你我两个:) –

+0

信息性的但...你如何防止你的应用程序实际创建多个记录(在操作的例子中,防止为用户添加多张信用卡)?是否将以下内容添加到用户模型中?验证:card_id,唯一性:{scope :: user_id} – rmcsharry