2013-11-28 38 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