10

要检查是否buyer.save会失败,我使用buyer.valid?

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
4

5 回答 5

14

如果未完成,则返回 false,与 . 相同savesave!如果你更喜欢,会抛出异常。我不确定是否有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
于 2011-01-17T13:19:25.487 回答
1

This may not be the best answer, but it seems to answer your question.

def self.validate_before_update(buyer)#parameters AKA Buyer.validate_before_update(params[:buyer])
# creates temporary buyer which will be filled with parameters
# the temporary buyer is then check to see if valid, if valid returns fail.
      temp_buyer = Buyer.new
# populate temporary buyer object with data from parameters
      temp_buyer.name = buyer["name"]
# fill other required parameters with valid data
      temp_buyer.description = "filler desc"
      temp_buyer.id = 999999 
# if the temp_buyer is not valid with the provided parameters, validation fails
    if  temp_buyer.valid? == false
        temp_buyer.errors.full_messages.each do |msg|
          logger.info msg
        end        
# Return false or temp_buyer.errors depending on your need.
        return false
    end

return true

end

于 2011-08-27T03:40:56.630 回答
1

你最好通过 before_save 在你的模型中检查它

before_save :ensure_is_valid
private 
def ensure_is_valid
  if self.valid?
  else
  end
end
于 2012-11-20T02:16:05.447 回答
1

update_attributes如果对象无效,该方法返回 false。所以就用这个结构

def update
  if @buyer.update_attributes(param[:buyer])
    my_update_database_method
  else
    ...
  end
end

如果您my_update_database_method只能在之前调用update_attributes,那么您应该使用合并方式,可能像这样:

def update
  @buyer = Buyer.find(params[:id])
  @buyer.merge(params[:buyer])
  if @buyer.valid?
    my_update_database_method
    @buyer.save
  else
    ...
  end
end
于 2011-01-17T14:06:46.817 回答
0

我遇到了同样的情况 - 需要知道记录是否有效并在更新保存之前执行一些操作。我发现有一种assign_attributes(attributes)方法 which updatemethod used before save。所以现在这样做可能是正确的:

def update
  @buyer = Buyer.find(params[:id])
  @buyer.assign_attributes(params[:buyer])
  if @buyer.valid?
    my_update_database_method
    @buyer.save
  else
    ...
  end
end
于 2020-08-20T10:17:17.887 回答