I have the following code in a likes_controller and it works fine as long as a thing has an owner. If not, it breaks.
def create
@thing = Thing.find(params[:like][:liked_id])
user = @thing.owner
current_user.like!(@thing)
current_user.follow!(user)
respond_with @thing
end
I’ve tried using
user = @thing.owner if @thing.owner.exists?
but I get a NoMethodError:
NoMethodError in LikesController#create
undefined method `exists?' for nil:NilClass
How do I check for the existence of an owner?
I also now notice I’ll have to put the second line (current_user.follow!(user)) in the block or it will break again…
Edit: This worked (using @Amadan’s answer):
def create
@thing = Thing.find(params[:like][:liked_id])
current_user.like!(@thing)
user = @thing.owner
if user
current_user.follow!(user)
end
respond_with @thing
end
Additional information: In case anyone ever actually uses this, I should point out that one more small change is necessary to get this to work. The above code errors out if a user tried to like a thing when they are already following the thing‘s owner.
so instead of
if user
I used
if user && !current_user.following?(user)
Hope this is helpful.
Insert this line:
Some might not like it on stylistic grounds, so you can use this alternative: