rails pass params in url
# Step 1: Define a route in config/routes.rb
get '/products/:id', to: 'products#show', as: 'product'
# Step 2: Create a link in your view passing params
<%= link_to 'Show Product', product_path(id: @product.id) %>
# Step 3: Access the params in the controller action
def show
@product = Product.find(params[:id])
end
Explanation:
1. Define Route: In the config/routes.rb
file, a route is established using get
for the 'show' action of the 'products' controller. :id
indicates a dynamic parameter that will hold the product's unique identifier.
Create Link with Params: In a view file (e.g.,
.html.erb
), a link is generated usinglink_to
. Theproduct_path
helper is used to generate the URL for the 'show' action of the 'products' controller, passing theid
parameter with the value of@product.id
.Access Params in Controller: Inside the 'show' action of the 'products' controller (
products_controller.rb
), theparams[:id]
is utilized to retrieve the specific product based on the passedid
parameter. This product information can then be used in the view associated with the 'show' action.