Hi guys,
I am currently trying to clean up my views. As you can see in the
example below, I’m having a new link to create a new resource
dynamically. The controller is given by the params[:controller]. This
way I create new action paths to all my resources with the same code.
I want now a similar thing but for the show action. The thing is that
I’ll need the instance variable. How can I set the instance variable
dynamically for a show action. I’ll have to add to the url_for method
below the ‘show’ parameter with the instance variable that comes from
the controller (example: @user, @message, @foo).
I tried the following first, but it didn’t worked since the id is then
processed as a string “@user”, so I get the following url: /users/
@user. I hope you guys can help me trying to solve this one. Thanks!
url_for(:controller => params[:controller], :action => “show”, :id =>
“@”+params[:controller].singularize)
<% link_to url_for(:controller => params[:controller], :action =>
"new") do %>
<%= image_tag("add.png") %>
<%= t('toolbar.new') %>
<% end %>
I found this and it worked:
:id => instance_variable_get("@#{params[:controller].singularize}")
One more thing though. When I try to do the link_to dynamically, I
generated the link_to urls using the url_for method. Is there any
other way to generate this routes dynamically without using the
url_for method? Thanks!
Hi –
On Sat, 12 Sep 2009, elioncho wrote:
Hi guys,
I am currently trying to clean up my views. As you can see in the
example below, I’m having a new link to create a new resource
dynamically. The controller is given by the params[:controller]. This
way I create new action paths to all my resources with the same code.
Do you mean you’re using the same template for all of these views? I
can’t quite get my bearings in the sequence of events you’re
describing.
David
–
David A. Black, Director
Ruby Power and Light, LLC (http://www.rubypal.com)
Ruby/Rails training, consulting, mentoring, code review
Book: The Well-Grounded Rubyist (The Well-Grounded Rubyist)
On Sat, Sep 12, 2009 at 1:00 AM, elioncho [email protected] wrote:
I found this and it worked:
:id => instance_variable_get(“@#{params[:controller].singularize}”)
One more thing though. When I try to do the link_to dynamically, I
generated the link_to urls using the url_for method. Is there any
other way to generate this routes dynamically without using the
url_for method? Thanks!
In
It says that #link_to relies on #url_for, so you can pass the hash of
{:controller, :action, :id} directly to it (without passing it to
#url_for first).
To get a string of the URL described by this controller/action/id
combination, that’s when you use #url_for.
I hope that answers your question.
Colin