繼承人我試圖實現的:如何在使用rails3創建新記錄之前檢查記錄是否存在?
- 我有一個標記系統。
- 當創建帖子時,會創建標籤(帖子has_many:tags,:through =>:tag_joins。
- 當使用標籤創建帖子時,會自動創建標籤連接)。
我想檢查標籤是否已經存在。如果是這樣,我想爲tag_join記錄使用現有的標記,而不是創建新的標記記錄。
這是我目前的代碼,這是行不通的。
class Tag < ActiveRecord :: Base
belongs_to :user
belongs_to :tag_join
belongs_to :post
before_create :check_exists
def check_exists
tag = Tag.where(:name => self.name, :user_id => current_user.id)
if tag.nil?
tag = Tag.create(:name => self.name, :user_id => current_user.id)
end
end
end
這不工作,雖然,在創建任務,我得到一個錯誤......(服務器實際上只是超時 - 我沒有收到具體的錯誤)。
任何想法?
Tokland說我告訴它再次創建標籤創建一個無限循環 - 所以我想這:
def check_exists
tag = Tag.find_by_name_and_user_id(:name => self.name, :user_id => current_user.id)
if tag != nil
self.id = tag.id
end
end
,仍然可以得到服務器超時
編輯:我不知道這很重要,但標籤添加的方式類似於「http://railscasts.com/episodes/73-complex-forms-part-1
它們嵌套在帖子表單中,並使用某些東西像這樣:
def tag_attributes=(tag_attributes)
tag_attributes.each do |attributes|
tags.build(attributes)
end
end
我想知道這是否阻止了整個工作?此外,在模型中使用current_user.id肯定似乎是一個問題......
編輯:
東西我已經想通了:這 不得不改變,我們使用之前的格式不正確,語法 - 通常用於.where方法。
def check_exists
@tag = Tag.find_by_name_and_user_id(self.name, self.user_id)
if @tag != nil
#return false
#[email protected]
end
end
現在的問題是這個,我可以知道它的標籤是否已經存在。但那又如何?如果我使用返回false選項,創建後會出現錯誤,並且不會創建連接記錄......另一個選項「self = @ tag」顯然不起作用。
代碼審查時間:當命名例程時,你想使用一個名字來表示它的功能。當它實際上可以創建記錄時,調用一個方法「check_exists」可能會更難找到「該記錄來自哪裏?」一旦你在應用中獲得了很多代碼。也許「get_tag」或「find_or_create_tag」會更好?像這樣的微妙事物會累積在應用程序中,並隨着時間的推移確定其可讀性和可維護性。 –
服務器超時可能與代碼無關。檢查它是否真的在運行,如果它在另一臺機器上,是否有連接。 –
其實只是發生在我的本地環境中。每次嘗試通過rails管理員手動創建標記時,服務器都會凍結。 – Elliot