开发者

Should my edit and new actions re-use the same view? (editing a post)

开发者 https://www.devze.com 2023-01-30 17:52 出处:网络
I have this setup in my routes: namespace :admin do resources :posts end so in my admin/posts_controller.rb I have my new, create and edit actions.

I have this setup in my routes:

namespace :admin do
     resources :posts

  end

so in my admin/posts_controller.rb I have my new, create and edit actions.

I want to re-use my new and edit view page somehow, b/c the page has allot of开发者_如何学运维 custom javascript etc. for the form and I don't want to repeat myself.

How can I do this?

i.e. for the edit page, I have to pre-populate the form fields and for the new page it is to be empty.

For a new page, it should post to the 'create' action, and for the edit I am thinking it should post to a different 'update' action (which is a PUT request as per my rake routes)?


Rails is pretty clever, a form like

<% form_for post do |f| %>
<% end %>

will post to the create action if post.new_record? == true and to the update action otherwise.

So, you can put the form in a partial, and render it inside your new/edit views, which will probably have different headings and copy.

Alternatively you can just have a single view and perform your own logic based on post.new_record? - but I'd advise against this because you'll end up with an unnecessarily complex view.

0

精彩评论

暂无评论...
验证码 换一张
取 消