Models @ data extraction

I’m building my first webapp…

I have db tables “users” and “posts”. Model for user is “has_many
:posts”. Model for post is “belongs_to :user”

In a slightly modified scaffold I can list all the posts and which user
wrote them (/post/list), but want to link the username to a list of
posts by that user.

How do I accomplish that?

Sorry for the newb question, but I’m a newb.
CE

comfort eagle wrote:

I’m building my first webapp…

I have db tables “users” and “posts”. Model for user is “has_many
:posts”. Model for post is “belongs_to :user”

In a slightly modified scaffold I can list all the posts and which user
wrote them (/post/list), but want to link the username to a list of
posts by that user.

How do I accomplish that?

Sorry for the newb question, but I’m a newb.
CE

first make sure that Post “belongs_to :user”

#view app/app/views/name_of_your_controller_here/list.rhtml
<% @posts.each do |post| %>

<%=h post.body %> - <%= link_to post.user.username, :action => 'user_posts', :id => post.user %>

<% end %>

#controller
def user_posts
@user = User.find(params[:id])
end

#view app/views/name_of_your_controller_here/user_posts.rhtml
<% @user.posts.each do |post| %>

<%=h post.body %>

<% end %>

first make sure that Post “belongs_to :user”

#view app/app/views/name_of_your_controller_here/list.rhtml
<% @posts.each do |post| %>

<%=h post.body %> - <%= link_to post.user.username, :action => 'user_posts', :id => post.user %>

<% end %>

#controller
def user_posts
@user = User.find(params[:id])
end

#view app/views/name_of_your_controller_here/user_posts.rhtml
<% @user.posts.each do |post| %>

<%=h post.body %>

<% end %>

Thanks!
CE

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs