2012-11-28 49 views
1

我在likes_controller中有以下代碼,只要thingowner就可以正常工作。如果不是,它會中斷。如何基於Rails中存在的屬性創建條件?

def create 
    @thing = Thing.find(params[:like][:liked_id]) 
    user = @thing.owner 
    current_user.like!(@thing) 
    current_user.follow!(user) 
    respond_with @thing 
    end 

我使用

user = @thing.owner if @thing.owner.exists? 

嘗試,但我得到一個NoMethodError:

NoMethodError in LikesController#create 

undefined method `exists?' for nil:NilClass 

如何檢查一個owner的存在?

我現在也注意到我得把第二行(current_user.follow!(user))的塊或將再次破...

編輯:這工作(使用@ Amadan的答案):

​​

附加信息:如果有人真的使用過這個,我應該指出一個小小的改變是必要的,以使其發揮作用。如果user試圖like a thing已經followingthingowner上述代碼錯誤。

所以不是

if user 

我用

if user && !current_user.following?(user) 

希望這是有幫助的。

回答

0

插入該行:

return unless user 

有些人可能不喜歡它的風格的理由,這樣你就可以用這個替代:

def create 
    @thing = Thing.find(params[:like][:liked_id]) 
    user = @thing.owner 
    if user 
    current_user.like!(@thing) 
    current_user.follow!(user) 
    respond_with @thing 
    end 
end 
+0

謝謝!我使用了第二個選項,但是我改變了一點,因爲我希望用戶喜歡這個東西,而不管它是否擁有一個所有者。 –

0

在Rails中,你可以這樣做:

user = @thing.owner if @thing.owner.present? 
+0

我已經嘗試過了,並且在LikesController中得到了'RuntimeError#create 被調用的id爲nil,whic如果我真的想要nil的id,使用object_id',如果我不檢查,就會得到同樣的錯誤。 –

+0

所有者如何在您的用戶類中定義?這是ActiveRecord嗎?東西是否屬於所有者? – ajstiles

+0

不是。它只在Thing類中定義:'belongs_to:owner,class_name:「User」,foreign_key:「owner_id」' –