Feng Ding
Feng Ding

Reputation: 17

In Ruby on Rails, how can I pass params[:id]?

In my home page I have:

# /views/static_pages/home.html.erb
<%= render @posts %>

and:

# /views/posts/_post.html.erb
<%= link_to 'haha', ?????? %>

Through the controller:

class StaticPagesController < ApplicationController
  def home
    @posts = Post.all.paginate(page: params[:page])
  end
end

and:

class PostsController < ApplicationController
  def show
   @post = Post.find(params[:id])
  end
end

I want to get the page:

# /views/posts/show.html.erb
<%= @post.name %>

by clicking the "haha" link to pass params[:id] to get the page /posts/:id.

But I dont know what to do to replace the ??????.

Also, the routes are:

Tradeincu::Application.routes.draw do  
  resources :users, :only => [:show]
  match '/users/:id', to: 'users#show', via: 'get'
  resources :posts
end

Upvotes: 0

Views: 1997

Answers (1)

Rafael Ramos Bravin
Rafael Ramos Bravin

Reputation: 660

There are many ways of doing this, you could use:

<%= link_to 'haha', post_path(post) %>

Or:

<%= link_to "haha", controller: "posts", action: "show", id: post %>

You can see the documetation along with some examples here.

Upvotes: 2

Related Questions