Reputation: 390
I am working on simple application to create your music collection. To add album to collection I am using Collection.rb model, it is working very well, but I decided to add a parameter :to_buy to Collection, and add second button "Add to wishlist".
collection_controller:
def create
@album = Album.find(params[:collection][:album_id])
current_user.collect!(@album)
@album.update_attributes(params[:collection][:to_buy])
respond_to do |format|
format.html { redirect_to @album }
format.js
end
end
Code for button to add album:
<%= form_for(current_user.collections.build(album_id: @album.id), remote: true) do |f| %>
<div><%= f.hidden_field :album_id %></div>
<div><%= f.hidden_field :to_buy, :value => true %></div>
<%= f.submit "Add to my wishlist", class: "btn btn-large btn-primary" %>
<% end %>
Album is adding to collection, but I want to send value true to :to_buy in collection, and it is still null. Could anyone explain why?
Upvotes: 1
Views: 2059
Reputation: 76774
Although GhostRider has valid information, let me explain what we'd do for this:
Custom Method
If you want to update one attribute, I'd make a custom method in your controller & route to it:
#config/routes.rb
resources :controller do
post :buy
end
#app/controllers/your_controller.rb
def buy
@album = Album.find(params[:collection][:album_id])
@album.update_attributes(to_buy: params[:collection][:to_buy])
respond_to do |format|
format.js
end
end
#app/views/
<%= form_for(current_user.collections.build(album_id: @album.id), url: buy_path(@album), remote: true) do |f| %>
<div><%= f.hidden_field :album_id %></div>
<div><%= f.hidden_field :to_buy, :value => true %></div>
<%= f.submit "Add to my wishlist", class: "btn btn-large btn-primary" %>
<% end %>
Upvotes: 1
Reputation: 10015
@album.update_attributes(params[:collection][:to_buy])
should be changed to
@album.update_attributes(:to_buy, params[:collection][:to_buy])
as you need to provide the attribute to be updated. I would also suggest to use where in place of find when querying over the model object.
Upvotes: 1