Reputation: 266910
In rails 3, is it possible to create a form_for that works for both new, update and edit actions?
If yes, how do I do this?
I have a admin section so my urls look like:
/admin/posts/ {new,update, edit}
Upvotes: 15
Views: 13237
Reputation: 4332
Because new needs to be sent to create, and edit needs to be sent to update a single form_for will not work.. unless (which I don't necessarily recommend) you place a tertiary operator in the form_form params
form_for(@post, :url => (@post.new_record? ? admin_posts_url : admin_post_url(@post)))
Because in your new action you are going to have Post.new which creates an object with a nil id, and in your edit action you will have Post.find(params[:id])
Upvotes: 22
Reputation: 452
Just let form_for
handle it:
controller:
class ControllerName
def new
@post = Post.new
end
def edit
@post = Post.find params[:id]
end
end
view:
<%= form_for [:admin, @post] do |f| %>
<% end %>
Upvotes: 30