huntz rahmadi
huntz rahmadi

Reputation: 136

Rails undefined method `persisted?'

I working using rails my project make API using mongodb

and I got this error:

NoMethodError: undefined method `persisted?'for ActionController::Parameters:0x000055f487fc4ac8

This error is in my controller on create method:

  def create
    if @merchant.order.push(get_params)
     render json: {:response => true, :status => "ok"}
    else
     render json: {:response => false, :status => "ok"}
    end
  end

  def get_params
  params.required(:order).permit!
  end

This is my model:

class Order
 include Mongoid::Document
 include Mongoid::Timestamps

 field :items
 field :grand_total, type: Integer

 belongs_to :merchant
end

I appreciate all kind of support, thank you.

Upvotes: 2

Views: 1304

Answers (2)

push accept an instance of Order and I assume you are passing something like ActionController::Parameters. Also, push always returns an association. I think if this failed, it would be with an exception and then the if makes no sense. I suggest to use create instead. So (assuming get_params is an instance of ActionController::Parameters or a Hash and that order is a has_many relationship):

if @merchant.order.create(get_params)
   render json: {:response => true, :status => "ok"}
  else
   render json: {:response => false, :status => "ok"}
  end
end

If it is a hash_one relationship, it should be something like:

params = get_params.merge(merchant: @merchant)
if @Order.create(params)
   render json: {:response => true, :status => "ok"}
  else
   render json: {:response => false, :status => "ok"}
  end
end

Upvotes: 3

mrzasa
mrzasa

Reputation: 23347

As far as I understand, push accepts a record (a model), not a hash of params:

label = Label.first
label.bands.push(Band.first)

Docs Mongoid checks if the model is persisted, that's why #persisted? is called on ActionController::Parameters that you pass there.

Try sth like

@merchant.order.push(Order.new(get_params))

if order is has_many relationship or

@merchant.order = Order.new(get_params)

if order is has_one relationship.

Upvotes: 0

Related Questions