2015-11-20 37 views
4

在我的Rails應用程序,用戶可以一起去的事件 -更好的辦法找到的has_many唯一記錄

user.rb

has_many :attendances 
has_many :events, through: :attendances 

event.rb

has_many :attendances 
has_many :users, through: :attendances 

...由一個由event_id,user_id和一些其他零碎組成的出勤表 -

att endance.rb

belongs_to :user 
belongs_to :writers_event 

在尋找特定出席時,我發現自己正在使用.where ... .first - 例如,

attendance = Attendance.where(user_id: @user.id, event_id: this_event_id).first 

而且這讓我感到我錯過了,我們談到了這種類型的情況使用類似find_by類 - 換句話說,你有信心,你正在尋找一些獨特的東西。這可能沒有關係,但是搜索一個集合然後從其中獲取第一個對象會感到浪費和錯誤。

有沒有更好的方法?

我環顧四周,這是最接近的,但沒有(我不認爲)真的覆蓋它。 How to display unique records from a has_many through relationship?

回答

3

您可以使用find_by此:

attendance = Attendance.find_by(user_id: @user.id, event_id: this_event_id) 

雖然在幕後,這是做一個查詢,並採取第一。

但是,你可以從這裏的軌道得到更多一點幫助:

current_user.attendances.find_by(event_id: this_event_id) 
+1

顯然你可以對事件做同樣的事情:'''my_cool_event.attendances.find_by(user_id:@ user.id)'' –

5

這其實很簡單:

attendance = Attendance.find_by(user_id: @user.id, event_id: this_event_id) 

你只是傳遞相同的條件find_by,並返回你的第一個記錄。

雖然有一個問題。通過使用find_by,如果沒有找到,你將得到零。如果您需要獲得ActiveRecord::RecordNotFound,如果沒有找到,可以使用find_by!

+0

有關nils和異常的find_by行爲非常重要,因爲它可以咬人。 –

2

試試這個:

Attendance.find_by_user_and_event(@user.id, this_event_id) 

如果沒有找到記錄則返回nil。如果你想提出異常

Attendance.find_by_user_and_event!(@user.id, this_event_id) 
+0

根據升級到Rails 4.0'除了find_by _...和find_by_之外的所有動態方法。 ..!已棄用' –

+0

是的,你是對的 –

+0

投票,如果你喜歡我的回答;) –