开发者

About default routing helpers, is there some redundancy?

开发者 https://www.devze.com 2023-03-09 07:27 出处:网络
Assuming post = Post.first, I can write a link with link_to \"First Post\"开发者_如何学C, post# I guess Rails here understand to which model the

Assuming post = Post.first, I can write a link with

link_to "First Post"开发者_如何学C, post  # I guess Rails here understand to which model the
                            # object "post" belongs

But to edit the post, the link is

link_to "Edit First Post", edit_post_path(post)

Is it possible to write something like:

link_to "Edit First Post", post, :type => :edit

so that it would be not necessary to specify to which model the object belong? Would not that be DRYer?


You can use method and action instead of type

See the documentation

Example:

link_to "Profile", :controller => "profiles", :action => "show", :id => @profile
# => <a href="/profiles/show/1">Profile</a>


This is a possible solution that I implemented. In application_helper.rb add the method:

def edit_path(item, other = {})
  send("edit_#{item.class.to_s.downcase}_path", item, other)
end

So now I can create edit links with:

link_to "Edit Post", edit_path(post)
link_to "Edit User", edit_path(user)

instead of

link_to "Edit Post", edit_post_path(post)
link_to "Edit User", edit_user_path(user)

I feel this is DRYer, but maybe it is just me.

0

精彩评论

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

关注公众号