Passing parameter in a Ruby function from HTML

2019-05-29 03:23发布

I have two files. .rb (with Ruby code) and .erb(HTML file with some ruby script). I am calling a Ruby function in .rb from .erb.

.erb

<a href="<%= url_for :action => :showProducts(i) %>">Click here</a> 

.rb

def showProducts(param)

//Some code

end

I am able to call a function without passing parameters to it. But as and when I pass parameters to function and then call it, I receive an error. I know this is the incorrect way to call a parametrized function from .erb. What is the correct way of calling a parameterized function from HTML?

3条回答
SAY GOODBYE
2楼-- · 2019-05-29 04:07

If you add in another key/value pair to the hash in url_for

<%= url_for :action => :showProducts, :product => "toaster" %>

Your URL should go from, say, http://localhost:3000/showProducts to http://localhost:3000/showProducts?product=toaster

Here, we're adding parameters to the GET request. To access these parameters in the controller we use the params hash. For example to get the product (toaster):

params[:product] #=> "toaster"
查看更多
放荡不羁爱自由
3楼-- · 2019-05-29 04:11

I found the solution to my problem :

<a href="<%= url_for :action => :showProducts, :id=> 'Hello' %>">  

.rb function:

def showProducts(param)

//Some code

end
查看更多
看我几分像从前
4楼-- · 2019-05-29 04:14

I found the solution

def showProducts 

 @params['product']

end
查看更多
登录 后发表回答