John Do wrote:
So you can’t really use a view call a controller/helper methods with
arguments via link?
You can call helpers from views, but not controller methods. Keep in
mind that the view is what’s going to get rendered to the client. So any
reference to a controller method is in the context of a client making
another request to the server, either via an ajax call or a standard
http request.
Let’s say I have a helper with method
def say_hello(string1, string2)
puts “#{string1} say hello to #{string2}”
end
I know in the view, I can do
<% say_hello(“Bob”, “Jill”) %>
and the console will print out “Bob say hello to Jill”.
If I would like this helper method by activated by a user click, what’s
the best way?
Something like
<% link_to “Say Hello”, say_hello(“Bob”, “Jill”) %> # if this actually
works
In the view, you would have the link_to point to a controller method,
and in the view refer to the helper method. Let’s start with an index
view that provides the link to say hello:
app/controllers/my_controller.rb
def index
end
def say_hello
end
app/views/my/index.html.erb
<%= link_to “Say Hello”, :action => :say_hello %>
app/views/my/say_hello.html.erb
<%= say_hello(‘Bob’, ‘Jill’) %>
app/helpers/my_helper.rb
def say_hello(string1, string2)
puts “#{string1} say hello to #{string2}”
end
You could also look into passing string1 and string2 from the client to
the server, in which case you’d change the index view to
<%= link_to “Say Hello”, :action => :say_hello, :string1 => ‘Bob’,
:string2 => ‘Jill’ %>
and the say_hello view to
<%= say_hello(params[:string1], params[:string2]) %>
Peace