加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:如何检查“update_attributes”是否会

发布时间:2020-12-16 21:47:18 所属栏目:百科 来源:网络整理
导读:要检查买方是否会失败我使用买方有效? def create @buyer = Buyer.new(params[:buyer]) if @buyer.valid? my_update_database_method @buyer.save else ... endend 我如何检查update_attributes是否会失败? def update @buyer = Buyer.find(params[:id]) i
要检查买方是否会失败我使用买方有效?
def create
  @buyer = Buyer.new(params[:buyer])
  if @buyer.valid?
    my_update_database_method
    @buyer.save
  else
    ...
  end
end

我如何检查update_attributes是否会失败?

def update 
  @buyer = Buyer.find(params[:id])
  if <what should be here?>
    my_update_database_method
    @buyer.update_attributes(params[:buyer])
  else
    ...
  end
end

解决方法

如果没有完成,则返回false,与save相同.保存!会抛出异常,如果你喜欢这样更好.我不知道是否有update_attributes !,但这是合乎逻辑的.

做就是了

if @foo.update_attributes(params)
  # life is good
else
  # something is wrong
end

http://apidock.com/rails/ActiveRecord/Base/update_attributes

编辑

然后你想要这个方法你必须写.如果你想预先检查params卫生.

def params_are_sanitary?
  # return true if and only if all our checks are met
  # else return false
end

编辑2

或者,取决于你的限制

if Foo.new(params).valid? # Only works on Creates,not Updates
  @foo.update_attributes(params)
else
  # it won't be valid.
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读