2011-01-07 56 views
1

我在與直通關聯的HABTM關係中有一個連接模型(詳情如下)。我試圖找到一條記錄....找到該記錄屬性的值...更改值並更新記錄,但是很難做到這一點。Rails - 如何更新連接模型中的記錄值?

模型設置是這樣的>>

User.rb

has_many :choices 
has_many :interests, :through => :choices 

Interest.rb

has_many :choices 
has_many :users, :through => :choices 

Choice.rb

belongs_to :user 
belongs_to :interest 

,並選擇有USER_ID ,interest_id,分數爲字段。

我找到了?對象?像這樣>>

@choice = Choice.where(:user_id => @user.id, :interest_id => interest.id) 

所以模型Choice有一個屬性叫做score。如何找到評分欄的值....和+ 1/-1然後重新保存?

我試圖

@choice.score = @choice.score + 1 
@choice.update_attributes(params[:choice]) 
flash[:notice] = "Successfully updated choices value." 

,但我得到 「未定義的方法得分」 ......我錯過了什麼?

+0

檢查!可能是你正在獲取@choice數組。 – 2011-01-07 02:44:29

回答

3

您可能需要使用.first運行實際查詢並返回結果:

@choice = Choice.where(:user_id => @user.id, :interest_id => interest.id).first 

...否則@choice僅持有一個活動關聯的對象......它沒有執行查詢呢。所以你需要指定。首先,獲得真正的模型更新的保持

2

您的查詢將返回一個選擇集。並且在更新之前,請務必檢查是否確實掌握了任何對象,以免您嘗試更新零:)

此外,如果您只想增加或減少字段,則可以使用方法。增量!或.decrement!這將立即更新到數據庫。

@choice.increment!(:score) 

因爲在你的情況下,如果params [:choice]包含得分值,它會覆蓋你以前分配的值。

+0

+1用於提示'。增量!'。好的提示。 – markquezada 2011-01-07 02:56:12

1

你已經有@user對象,所以使用:

@choice = @ user.choices.find_by_interest_id(interest.id)