说我正在建立一个博客.我有两个资源:文章和用户.每个用户都有很多文章,每篇文章都属于一个用户:
- rails g scaffold User name:string email:string
- rails g scaffold Article user_id:integer title:string content:string
用户模型:
- class User < ActiveRecord::Base
- has_many :articles
- end
文章模型:
- class Article < ActiveRecord::Base
- belongs_to :user
- end
现在,在我的文章索引上,我可以做类似的事情:
- …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>
我对用户名的模型关联所需要的只是在response_to之前将“@articles = Article.all”放在索引操作上.太酷了!
如果我想在我的主页上使用我的Home控制器上的索引操作列出所有这些文章(我为了简单而在这里跳过分页),该怎么办?
我知道我可以在家庭控制器中做这样的事情:
- class HomeController < ApplicationController
- def index
- @articles = Article.joins(:user)
- end
- end
…然后我可以在我的home->索引视图中访问这些数据:
- <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>
第一个问题:访问所有文章的用户数据时,我应该使用:join还是:include?它们似乎都有效,但我想知道在这种情况下哪一个是正确的,哪一个通常表现得更快.
- @articles = Article.joins(:user)
航班吗
- @articles = Article.includes(:user)
第二个问题:在我的文章脚手架(构建迁移)中,我应该使用user_id:integer或user:references.他们做同样的事情,还是比另一个更受欢迎?如果我使用:integer作为字段类型,是否建议我也为它添加一个索引(add_index:articles,:user_id)?我找到了一个很棒的RailsCast,它解释得很好,但我想知道是否有其他人有另一种意见.
如果它有帮助,我在Rails 3.2.2上.
谢谢!
解决方法
- @articles = Article.includes(:user)
使用@articles = Article.joins(:user),您将只获得具有User的文章,并且当您在任何这些文章上执行article.user时,它将生成新的sql请求.
有关更多信息:@L_502_1@(如果您还没有阅读过这套指南,我强烈建议您现在就这样做).
第二个问题:
我使用user_id:整数形式.我不确定用户:引用可以在rails g scaffold命令行中使用. “articles.user_id”列上的索引将在查找特定用户的文章时提高检索速度.仅当您的应用程序将执行此类搜索时才添加此索引.