如何根据Rails中属性的存在创建条件?

时间:2012-11-28 00:39:31

标签: ruby-on-rails nomethoderror

我在likes_controller中有以下代码,只要thingowner,它就可以正常工作。如果没有,它就会破裂。

  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?

但我得到NoM​​ethodError:

NoMethodError in LikesController#create

undefined method `exists?' for nil:NilClass

如何检查是否存在owner

我现在也注意到我必须将第二行(current_user.follow!(user))放入块中,否则它将再次中断......

编辑:这有效(使用@Amadan的答案):

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

附加信息:如果有人真正使用过这个,我应该指出,为了让它发挥作用,还需要做一个小的改动。如果userlike thing following thing owner if user if user && !current_user.following?(user) 时{{1}}尝试{{1}} {{1}},则上述代码会出错。

所以而不是

{{1}}

我用过

{{1}}

希望这有用。

2 个答案:

答案 0 :(得分:0)

在Rails中你可以这样做:

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

答案 1 :(得分: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