Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to update nested attributes

I'm working on a very basic practice application where a user can create multiple quotations. The problem I'm having is that I can't update my quotations. I've many things and have read through other questions here and on google, but can't figure out what I am doing wrong. Here is my code:

#User Model
    class User < ActiveRecord::Base
      has_many :quotations, :dependent => :destroy
      attr_accessible :quotations
      accepts_nested_attributes_for :quotations, :allow_destroy => true
    end

#Quotations Model
class Quotation < ActiveRecord::Base
  attr_accessible :quote_text, :author, :quote_type, :category, :tags, :user_id
  belongs_to :user
end

Quotations Controller

class QuotationsController < ApplicationController
  before_filter :get_user

  def get_user
    @user = User.find(params[:user_id])
  end 

  def edit
    @quotation = @user.quotations.find(params[:id])
  end

  def update
    @quotation = @user.quotations.find(params[:id]) 
    if @quotation.update_attributes(params[:id])
      redirect_to user_quotation_path :notice  => "Successfully updated quotation."
    else
      render :action => 'edit'
    end
  end    

end
like image 573
Edward Castaño Avatar asked Aug 15 '26 18:08

Edward Castaño


1 Answers

You are passing the wrong params hash into the update_attributes call. It should be

if @quotation.update_attributes(params[:quotation]).

To clarify, passing :id or :quotation isn't doing anything special. Symbols in Ruby are just immutable string. So using :id or :quotation is the equivalent of passing a string "id" or "quotation". params[] is a hashmap of all the form parameters posted by your page.

In the params hash, there is a key of the type you are passing (in this case quotation) which has a value of another hash containing all of the posted fields associated to the quotation in your view and the values of those fields.

The ID, controller and action values in the params hash comes from the route values from the url.

E.g.

params[] = 
{ 
      :controller => 'quotations',
      :action => 'edit',
      :id => '1',
      :quotation => 
      {
          :quote_text=> "Blah", 
          :author=> "Steve", 
          :quote_type=> "1", 
          :user_id=> "6"
      }
}
like image 56
dnatoli Avatar answered Aug 17 '26 10:08

dnatoli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!