Prabhakaran
Prabhakaran

Reputation: 4013

undefined method `update_attributes' for #<Array:0xb5d61608> rails 4

I have the below action in my controller

cust = Customer.where(email: '[email protected]').pluck(:post_id)
@posts = Post.find(cust)
if params[:status]
  if @posts.update_attribute(:customer_id, customer_id)
    respond_to do |format|
      format.json { render json: 'test'}
    end
  end
end

The above update_attribute is throwing undefined method error.

cust will return array of ids such as [1,2,3]

How can I do this

Upvotes: 0

Views: 1380

Answers (3)

Rashmi Nair
Rashmi Nair

Reputation: 339

Try this

cust = Customer.where(email: '[email protected]').pluck(:post_id)

Post.update_all({:customer_id, customer_id}, {id: cust})

we can include the where clause in the update_all query itself

Upvotes: 0

Michael Moulsdale
Michael Moulsdale

Reputation: 1488

try to alter the queries in the following way

cust = Customer.where(email: '[email protected]').first.pluck(:post_id)

This will return a single customer, then do the same thing with post @posts = Post.where(id: cust).first

However, if you want multiple records in @posts, then you'll need to loop through them all and update individually.

@posts.each do |post| if post.update_attribute(:customer_id, customer_id) end end

Upvotes: 0

Jun Zhou
Jun Zhou

Reputation: 3070

Try:

@posts = Post.where(id: cust)
@posts.update_all(customer_id: customer_id)

It constructs a single SQL UPDATE statement and sends it straight to the database.

Upvotes: 4

Related Questions