Rails - Is there a way to update a single attribute?
14,263
Solution 1
<%= 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
Solution 2
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
Author by
Samth
Updated on July 12, 2022Comments
-
Samth almost 2 years
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 thisboolean
and just thatMy 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 theplayer
that owns thisteam
can change theboolean
ofsquad
. 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? -
Samth almost 13 yearsThanks for the answer :). I'm trying to create a link to it but isn't working, its updating all the models in the page :/ I have a query to find the squads in question, do you think this is the best way or there is other possible thing I could do?
-
Samth almost 13 yearsThanks for the answer. I edited my question. Could you change the link my link into the one you proposed? :)
-
Samth almost 13 yearsThanks! That was the missing part :)
-
fl00r almost 13 years@Aditya Sanghi, yes, it is just a mistype of course and it is not the point of the answer
-
Aditya Sanghi almost 13 yearsI thought the point of the question was how to update a single attribute on a model not multiple. Regardless glad that the poster got the solution. :) cheers
-
undefinedvariable over 11 years@fl00r's answer helped me figure out my error. I did it without the method in the controller though.
<% boolval_state = modelname.boolval ? "Y" : "N"; boolval_flip = modelname.boolval ? false : true; %>
<%= link_to boolval_state, modelname_path(modelname, "modelname[boolval]" => boolval_flip), method: :put %>