开发者

String to method/function call in ruby?

开发者 https://www.devze.com 2022-12-20 22:58 出处:网络
I want to make my rails controller more flexibl开发者_JAVA技巧e and try to create some Meta foo for it.

I want to make my rails controller more flexibl开发者_JAVA技巧e and try to create some Meta foo for it.

I have a problem with the redirect_to method. Can I convert the "edit_admin_post_path()" method from a string or better read out the controller name and pass it dynamicly?

this is my code for "post" in my Admin::Posts controller.

respond_to do |format|
  format.html { redirect_to(edit_admin_post_path(@object)) }
end

thanks!


I don't understand what you want to do, however there are multiple ways to achieve your request. One is

what = "post"
respond_to do |format|
  format.html { redirect_to(send("edit_admin_#{what}_path", @object)) }
end

Keep in mind, edit_admin_post_path is equal to

url_for(:controller => "admin/posts", :action => "edit", :id => @object)

So you can always do

what = "post"
respond_to do |format|
  format.html { redirect_to(url_for(:controller => "admin/#{what.pluralize}", :action => "edit", :id => @object)) }
end

or better, if you want to dynamically redirect to the edit action according to current controller, just pass the hash of options.

respond_to do |format|
  format.html { redirect_to(:action => "edit", :id => @object) }
end
0

精彩评论

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