update_attributes with none-standard form
I have cobbled together a form due to some oddities in my code and routes. Things work for adding data to the database, but I can't quite seem to figure out how to update data. Here is some code.
new.html.erb
<% form_tag '/list' do %>
Episodes Completed:
<%= text_field_tag "completed" %>
Watch Status
<%= collection_select(nil, 'id', @show_status, :id, :state) %>
<%= hidden_field_tag('show_id', @show.id) %>
<%= submit_tag 'Add' %>
<% end %>
edit.html.erb
<% form_tag("/list/#{@show_completion.show.id}", :method => :put ) do %>
Episodes Completed:
<%= text_field_tag "completed", @show_completion.episodes_completed %>
Watch Status
<%= collection_select(nil, 'id', @show_status, :id, :state) %>
<%= hidden_field_tag('show_id', @show_completion.show.id) %>
<%= submit_tag 'Edit' %>
<% end %>
Here is the controller's Create and Update methods
def create
@show_completetion = ShowCompletionStatus.new
@show_completetion.user_id = current_user.id
@show_completetion.episodes_completed = params[:completed]
@show_completetion.status_state_id = params[:id]
@show_completetion.show_id = params[:show_id]
@show_completetion.save
end
def update
@show_completion = ShowCompletionStatus.find(params[:id])
@show_completion.episodes_completed = params[:completed]
@show_completion.status_state_id = params[:id]
@show_completion.show_id = params[:show_id]
if @show_completion.update_attribute('episodes_completed', params[:completed])
redirect_to "/list/#{current_user.username}"
else
redirect_to "/list/#{params[:id]}/edit"
end
end
Here are my routes for these:
match "list/" => "list#create", :via => :post
match "list/new/:show_id" => "list#new", :constraints => { :s开发者_如何学JAVAhow_id => /[0-9]+/ }
match "list/:id/edit" => "list#edit", :constraints => { :id => /[0-9]+/ }, :via => :get
match "list/:id" => "list#update", :constraints => { :id => /[0-9]+/ }, :via => :put
I have been trying different things to get this to work for the better part of 4 hours now. I think I am just missing something, but I just can't see it.
Is there a better way to do the form that makes it work better?
Any help is appreciated.
I solved this issue by making a hash and passing it to the update attributes with the key value pairs of what the objects attributes would be. Since updates_attributes takes a hash and not an object it was a simple solution once the connection was made.
Try to replace your update_attribute
call for a save
call.
Also, if you're writing everything from scratch instead of using the builtins, try to use save!
instead of save
: it will raise an exception if it fails, unlike the plain save
that just returns false
.
精彩评论