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
Share:
14,263
Samth
Author by

Samth

Updated on July 12, 2022

Comments

  • Samth
    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 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?

  • Samth
    Samth almost 13 years
    Thanks 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
    Samth almost 13 years
    Thanks for the answer. I edited my question. Could you change the link my link into the one you proposed? :)
  • Samth
    Samth almost 13 years
    Thanks! That was the missing part :)
  • fl00r
    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
    Aditya Sanghi almost 13 years
    I 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
    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 %>