views:

32

answers:

2

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 %>
A: 

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 :]

j.
I think he should use the default update action that rest provides to update a field of his model. Creating a new action to do that is highly unrecommended.
robertokl
A: 

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} %>
robertokl
Cool, I'll try it out!
James