Reputation:
I am trying to Implement a feed of all post from a multi user blog. I want to know where to define this method and how to define it to be as "RESTFUL" as possible.
I am thinking of putting it in the posts index view but the problem is i dont have access to the users name attribute that created that post. The index action currently looks like this
def index
@posts = Post.all
end
and doing this:
def index
@user=User.find(params[:user_id])
@posts = @user.posts.all
end
raises an error " Couldn't find User without an ID "
App info: I have a users resource and a post resource (nested in the users). That is pretty much it. Thanks
Clarification:
Thanks guys for the assistance so far. My controllers index action is defined as follows
def index
@users = User.all
@posts = @users.collect { |user| user.posts }.flatten
end
The issue i am having is displaying the posts users name in the view. for example this works but only displays the posts attibutes:
<% @posts.each do |post| %>
<ul>
<li> <%= post.title %>
<%= post.content %>
<%= user.name %> or <%= @user,name %> #This does not work
</li>
</ul>
I am not sure if i wrote the block correctly. Hope this clarifies things
Upvotes: 0
Views: 313
Reputation: 4880
You can do something like this:
def index
@posts = Post.includes(:user)
end
# view
<ul>
<% @posts.each do |post| %>
<li>
<%= post.title %>
<%= post.content %>
<%= post.user.name %>
</li>
<% end %>
</ul>
Upvotes: 3
Reputation: 2381
First you need to query the users that you want...
def index
# For example...
@users = User.all # or...
@users = User.find_by_group_id(params[:group_id]) # etc...
# Then, from your users, you need to collect the posts...
@posts = @users.collect { |user| user.posts }.flatten
end
This would get an array of each users posts, then flatten it to a single array. At that point you can then sort the array to whatever you want.
I don't know what exactly you're looking for, but these are just some ideas. Depending on how you're app is structured (and the groups of users are organized), you'll likely want to use some sorted of nested resource like juanpastas posted.
Upvotes: 0
Reputation: 21795
You should be visiting the wrong URL.
First, check your parameters in your server console, you should not see user_id
param.
To set this param, use the correct route
user_posts_path(an_user_instance)
I suppose you have in routes:
resources :users do
resources :posts
end
Upvotes: 0