Good. I am new to Rails, and I know that this was asked before, but I still don't understand how to approach the next general problem. I can make the association work, but something magical to do and run rails with bad habits is not what I want to do.
Say I'm building a blog. I have two resources: articles and users. Each user has many articles, and each article belongs to one user:
rails g scaffold User name:string email:string rails g scaffold Article user_id:integer title:string content:string
User Model:
class User < ActiveRecord::Base has_many :articles end
Article Model:
class Article < ActiveRecord::Base belongs_to :user end
Now, in my article index, I can do something like:
β¦table headers... <% @articles.each do |article| %> <tr> <td><%= article.user.name %></td> <td><%= article.title %></td> <td><%= article.desc %></td> <td><%= article.content %></td> <td><%= link_to 'Show', article %></td> <td><%= link_to 'Edit', edit_article_path(article) %></td> <td><%= link_to 'Destroy', article, confirm: 'Are you sure?', method: :delete %></td> </tr> <% end %> </table>
And all I need for this model association for the username is to put "@articles = Article.all" on the index action before response_to. Pretty awesome!
What if I want to list all of these articles (I just skipped paging here for the sake of simplicity) on my home page using the index action on my home controller?
I know that I can do something like this in the Home Controller:
class HomeController < ApplicationController def index @articles = Article.joins(:user) end end
... and then I can access this data in my home index:
<div class="row"> <% @articles.each do |article| %> <div> <h3><%= link_to article.title, :controller => "articles", :action => "show", :id => article.id %></h3> <small>Posted on <%= article.created_at %> by <a href="#"><%= article.user.name %></a></small> </div> <% end %> </div>
First question: When accessing user data for all articles, should I use: join or a: includes? They both seem to work, but I wonder which one is right in this situation, and which usually works faster.
@articles = Article.joins(:user)
-vs-
@articles = Article.includes(:user)
Second question: In my project for the article (creating migration), you should use user_id: integer or user: reference. Do they do the same or prefer each other? If I use: integer as the type of the field, is it recommended that I add an index for it (add_index: articles ,: user_id)? I found a great RailsCast and it does a great job explaining, but I'm wondering if anyone has a different opinion.
If this helps, I'm on Rails 3.2.2.
Thanks!