保存不保存在控制器中

时间:2016-10-20 16:09:59

标签: ruby-on-rails ruby activerecord

无法弄清楚为什么不能保存..

我为了简洁而缩短了我的代码,省略了end和其他不重要的事情。

我在控制器中遇到了这个问题:

create_barbie = Barbie.new(params.require(:barbie).permit(:merchant_id,
:auth_token,:marketplace))
huh = create_barbie.save! #this is returning ActiveRecord::RecordNotSaved   
#(Failed to save the record)

在失败之前create_barbie看起来像这样:

id: nil, merchant_id: "A340I3XXXX", auth_token: "13245", marketplace:   
"abcded", created_at: nil, updated_at: nil, shopify_domain: nil, shop_id:  
nil, three_speed: nil>

所以我的params过得很好,并且已经填充,只是某些原因记录没有保存?

在我的Barbie模型中,我有以下内容:

class Barbie < ActiveRecord::Base
  belongs_to :shop
  validates :merchant_id, presence: true
  validates :auth_token, presence: true
  before_save :assign_three_speed
  NON_US_MARKETPLACES = ["1234", "abcd"]

Barbie模型中的私有方法中,我有:

private
  def assign_three_speed
    if NON_US_MARKETPLACES.include?(marketplace)
      self.three_speed = false
    else
      self.three_speed = true   
    end
  end

所有数据都是正确的,字段正在设置,它只是没有保存..不知道为什么??

2 个答案:

答案 0 :(得分:2)

首先提示一点:当你不确定它为什么会失败时,在开发过程中使用save!。这会引发验证错误的异常,而不仅仅是返回false

对于您的问题,请使用permithttp://api.rubyonrails.org/classes/ActionController/Parameters.html

Barbie.new(params.require(:barbie).permit(:merchant_id, ...))

答案 1 :(得分:2)

The issue is, indeed, with your before_save hook. The thing with the hook is that it can cancel the save operation if it returns false. And in your case it does return false. If you don't intend to cancel save, return a truthy value always.

  def assign_three_speed
    if NON_US_MARKETPLACES.include?(marketplace)
      self.three_speed = false
    else
      self.three_speed = true   
    end

    true # don't cancel save
  end