Reputation: 7835
In my Rails API, I have the following line for updating a Model. As you can see, it accepts a lot of parameters. But, I have a few questions about this that the current documentation doesn't answer...
@updated_special_deal.update_attributes(:category => params[:category], :title => params[:title], :excerpt => params[:excerpt], :description => params[:description], :original_price => params[:original_price], :deal_price => params[:deal_price], :provider => params[:provider], :product_link => params[:product_link], :conditions => params[:conditions], :phone_number => params[:phone_number], :street => params[:street], :city => params[:city], :postal_code => params[:postal_code], :state => params[:state], :country => params[:country], :expires => params[:expires], :image_file_name => params[:image_file_name], :image_content_type => params[:image_content_type], :image_file_size => params[:image_file_size], :image_updated_at => params[:image_updated_at], :public => true)
On trying this PUT request via external Client App. I get this response below...
Started PUT "/api/v1/1/special_deals/47?title=The+greatest+deal+ever" for 127.0.0.1 at 2013-04-12 14:39:15 -0700
Processing by Api::V1::SpecialDealsController#update as JSON
Parameters: {"title"=>"The greatest deal ever", "servant_id"=>"1", "id"=>"47"}
ActiveRecord::RecordInvalid - Validation failed: Provider can't be blank, Description can't be blank:
Sure, I wrote those rules in the Model. But, I'm not trying passing in the Provider attribute or the Description attribute. So, what's happening here?
EDIT Rephrasing the question: How do I write update_attributes so that it only updates the attributes included in the PUT request?
Upvotes: 0
Views: 228
Reputation: 29880
You should pass params to be updated inside of a root element with your model name. So your params should be something like:
{"servant_id"=>"1", "id"=>"47", "special_deal":{"title"=>"The greatest deal ever"}}
In your controller action, you can load the model and relationships, and then update the model from the "special_deal" params.
def update
servant = Servant.find(params[:servant_id])
@special_deal = SpecialDeal.find(params[:id])
@special_deal.servant = servant
@special_deal.update_attributes(params[:special_deal])
end
update_attributes
simply takes a hash and updates the attributes in the hash. If you have your params be as I mentioned, then params[:special_deal]
will be equivalent to {"title" => "The greatest deal ever"}
. Passing that hash into the update attributes call will update only the title
attribute on your model.
Upvotes: 1
Reputation: 96594
Try:
Removing:
:provider => params[:provider] and :description => params[:description]
or make sure they are provided with actual values.
Your model has validations which require either valid values or none (depending on the exact validations used).
Upvotes: 0