Rails - Is there a way to update a single attribute?
I开发者_如何学Go 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?
<%= 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
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
What's the name of your attributes ?
Since it belongs to player
, you can access it with player.squad.name_of_your_attributes = new_value
. Don't forget to save
your object if you want the changes to be saved in your DB.
Also, you could read that
EDIT: fl00r answered your edited question, no need that i repeat what he wrote.
精彩评论