Reputation: 925
First part:
I have an index page that lists all the posts in my app. I want to be able to click on the links title and have it redirect me to the posts show page. Here is my index page.
<% provide(:title, "All Posts") %>
<% @posts.each do |post| %>
<div>
<h2><%= link_to post.title.titleize, post %> by <%= post.author.name.titleize %></h2>
<div><%= post.body %></div>
</div>
<% end %>
When I try to go to my index
page I get
undefined method `post_path' for #<#<Class:0x007fc6df41ff98>:0x007fc6df436e78>
I pretty sure its because of the post
in my link_to, but I dont know what I would put there to make it go to the right place. When I run rake routes
it shows that the posts#show action is
user_post GET /users/:user_id/posts/:id(.:format) posts#show
so I tried replacing post
with user_post_path(post)
but then I get
No route matches {:action=>"show", :controller=>"posts", :user_id=>#<Post id: 4, title: "werwef", body: "erfwerfwerf", user_id: 3, created_at: "2013-08-16 20:05:43", updated_at: "2013-08-16 20:05:43">, :id=>nil, :format=>nil} missing required keys: [:id]
What should it be changed to?
Second part:
I have <%= post.author.name.titleize %>
to print out the users name that posted the post, and Im getting it from a method I defined in my post model
def author
User.find(self.user_id)
end
Is this the best way to do this? Before I made the method, I tried post.user.name
, but that didn't work and just told me there was no method for user
defined. Thanks for the help.
Upvotes: 2
Views: 1683
Reputation: 4976
First Part
Since these are nested paths, have you considered passing the User as well as the Post? Your final URL expects a user_id
as well as a post_id
, so you may need to call the following:
<%= link_to user_post_path(post.user, post) %>
The documentation is here: Rails Guide on Nested Resources
Extracted from this SO question.
Second Part
You might miss the association calls :
Post.rb
belongs_to :user
User.rb
has_many :posts
And then you can use post.user
Upvotes: 4