Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Is there a way to update a single attribute?

I was just wondering, I have a model that, besides the id's from other models (FK), it has a single attribute boolean. I want to know how can I create a button that changes this boolean and just that

My model in question is this one:

class Squad
 belongs_to :player
 belongs_to :team
end

I want to create a button on the team#show page so the player that owns this team can change the boolean of squad. How can I do this and how would look like my controllers?

Thanks :)!

-Edit-

I'm using a link like this:

<%=link_to("Change status", squad_path(sqd, :status => true), :method => :put, :confirm => "Sure?")%>

Where sqd is part of my query. Is this link wrong?

like image 474
Samth Avatar asked May 22 '11 18:05

Samth


2 Answers

<%= link_to("Change status", squad_path(sqd, "squad[status]" => true), :method => :put, :confirm => "Sure?") %>

in your controller (it is pretty common)

def update
  @squad = Squad.find params[:id]
  if @squad.update_attributes params[:squad]
    ...
  end
end
like image 100
fl00r Avatar answered Sep 30 '22 05:09

fl00r


Yes there is. The method is called "update_attribute". It takes two arguments, the name of the field and the value.

  squad.update_attribute(:boolean_field,true) # or false

Based on updated question

def update
  @squad = Squad.find(params[:id])
  if @squad.update_attribute(:status,params[:status])
    ...
  end
end
like image 39
Aditya Sanghi Avatar answered Sep 30 '22 03:09

Aditya Sanghi