2012-11-06 34 views
0

我有一個表單來創建帖子。此表單在帖子上也有標籤,並由用戶擁有。表單使用虛擬屬性:tag_ids。如何在模型中不使用current_user

我想做這樣的事情,你find_or_create_by_name_and_user_id,然後只是通過current_user.id。

def tag_ids=(tags_string) 
    self.taggings.destroy_all 
    tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq 
    tag_names.each do |tag_name| 
     tag = Tag.find_or_create_by_name_and_user_id(tag_name, current_user.id) 
     tagging = self.taggings.new 
     tagging.tag_id = tag.id 
    end 
end 

從我讀到的這不是它應該如何工作。應該在PostsContoller創建方法中調用當前用戶。

def create 
    @post = Post.new(params[:post]) 
    @post.user = current_user 
    respond_to do |format| 
    if params[:commit] 
    @post.save 

... 結束

這是我堅持。如果參數傳遞所有屬性,我怎樣才能將current_user id注入到具有:name和:user_id屬性的標籤模型中?

我也讀過,這應該工作,因爲我的關聯。

User - has_many posts; has_many標籤

後 - belongs_to用戶; has_many標籤; has_many標籤通過標籤

標籤 - 有許多標籤; has_many通過標籤發帖; belongs_to用戶

Tagging - belongs_to post; belongs_to的標籤

回答

0

模型不能得到CURRENT_USER,你必須明確地傳遞,也有可能是夫妻黑客要做到這一點的,但簡單的方法是,用戶已經存儲在後如此self.user.id是有用 如果以上方法在post模式中,post用戶標記用戶。

Tag.find_or_create_by_name_and_user_id(tag_name, self.user.id)

+0

這對我不起作用。我得到了「被調用的ID爲零,這將錯誤地爲4 - 如果你真的想要的ID爲零,使用object_id」這是在self.user.id – ebbflowgo

+0

什麼是self.user的價值 – Amar

+0

價值self.user是零 – ebbflowgo

相關問題