Reputation: 2902
Rails newbie here.
I have a list of items
which can have a status
represented by an integer (right now its just 1=active 0=inactive).
What I want is next to each item
a link to change the status
of that item. So it might look like this:
A nice item - Enable
Another pretty item - Disable
I can't think of how to make the link work. I just want a user to click the link and then the page refreshes and the item
get updated.
This doesn't work:
<%= link_to "Enable", :controller => "items", :action => "update", :status => 1 %>
Upvotes: 0
Views: 776
Reputation: 1909
If you have the default rails controller implemented, this
<%= link_to "Enable", :controller => "items", :action => "update", :status => 1 %>
is not working because in the update action rails calls
@item.update_attributes(params[:item])
and the status is going to the controller as
params[:status]
Beside that, to call update the method must be PUT.
Try changing the link to something like:
<%= link_to "Enable", :controller => "items", :action => "update", :method => :put :item => {:status => 1} %>
Upvotes: 1
Reputation: 8461
I'd do something like
# view
<% @items.each do |item| %>
# ...
link = link_to_remote((item.active? "Disable" : "Enable"), :url => {
:controller => "items", :action => "swap_status", :id => item.id
})
<%= item.name %> - <%= link %>
<% end %>
# item model
class Item < ActiveRecord::Base
# ...
def active?
self.status == 1
end
end
# items controller
class ItemsController < ApplicationController
# ...
def swap_status
item = Item.find(params[:id])
new_status = item.active? ? 0 : 1
item.update_attribute(:status, new_status)
# and then you have to update the link in the view,
# which I don't know exactly how to do yet.
end
end
I know it's incomplete... but I hope it helps you somehow :]
Upvotes: 1