Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is a fairly straight forward use of Ruby on Rails. I recommend reading <a href="http://guides.rubyonrails.org/active_record_basics.html" rel="nofollow noreferrer">Active Record Basics</a> to get up to speed.</p> <p>First, you should have a belongs_to relationship between Posts and Users that looks like this:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :posts end class Post &lt; ActiveRecord::Base belongs_to :user end </code></pre> <p>This adds a <code>.posts</code> method to the <strong>User instance</strong> and a <code>.user</code> method to the <strong>Post instance</strong>.</p> <p>Then you have to make a decision about how you want the URL structure of your application to work. Here are a few options from the top of my head:</p> <ol> <li>/posts?user=:user_id</li> <li>/posts/by/:user_id</li> <li>/users/:id/posts</li> </ol> <p>Given the relationship between a User and their Posts, my recommendation (and I believe the general "Rails Way") would be #3. So, let's add the routes to <code>config/routes.rb</code>:</p> <p>The short way to create JUST that route:</p> <pre><code>get 'users/:id/posts' =&gt; 'users#posts', :as =&gt; :user_posts </code></pre> <p>The long way to create the route based on <a href="http://guides.rubyonrails.org/routing.html" rel="nofollow noreferrer">resources</a>:</p> <pre><code>resources :users do member do get :posts end end </code></pre> <p>Both approaches will provide a helper method called <code>user_posts_path</code> and one called <code>user_posts_url</code> which can be used in your view to link to the list of user posts using the <strong>link_to</strong> helper method:</p> <pre><code>&lt;%= link_to post.user.name, user_posts_path(post.user) %&gt; </code></pre> <p>Now, you have to add the controller action in <code>app/controllers/users_controller.rb</code>:</p> <pre><code>class UsersController &lt; ActionController::Base def posts @user = User.find(params[:id]) @posts = @user.posts end end </code></pre> <p>and then add your HTML/ERB code to <code>app/views/users/posts.html.erb</code></p> <pre><code>&lt;% @posts.each do |post| %&gt; &lt;%= post.inspect %&gt; &lt;% end %&gt; </code></pre> <p>That should give you the basic ability to show a user's posts. You can enhance it by reusing a post partial or some other nice shortcuts, but I'll leave that as an exercise for you to figure out.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload