0

我需要的是在一次搜索中搜索故事标题以及故事属于谁。

显然这是不对的,但它让我明白了:

@stories = Story.where("user.display_name LIKE ? And title LIKE ?", 
             "%#{@query}%", "%#{@query}%").limit(500).page(params[:page])

故事属于用户,用户有很多故事。不知道我还需要在这里放什么,而且我还没有真正理解任何似乎相关的答案。

谢谢。

更新

<% if @stories.size == 0 %>
    Sorry, there were no stories found.
<% else %>
    <table class="sortableTable table-striped" style="width: 100%; text-align: left;">
      <thead>
        <tr>
         <th width="55%">Title</th>
         <th width="25%">User</th>
         <th width="10%">Created At</th>
         <th width="10%">Updated At</th>
        </tr>
      </thead>
      <tbody>
        <% @stories.each do |s| %>
        <tr>
         <td width="55%"><div class="span5 search_result"><%= link_to s.title, s %></div></td>
         <td width="25%"><div class="span3 search_result"><%= link_to s.user.display_name, s.user %></div></td>
         <td width="10%"><div class="span3 search_result"><%= time_ago_in_words(s.created_at) %> ago</div></td>
         <td width="10%"><div class="span3 search_result"><%= time_ago_in_words(s.updated_at) %> ago</div></td>
        </tr>
        <% end %>

      </tbody>
    </table>
<% end %>
4

1 回答 1

0

如果您不想急切加载与故事关联的用户对象:

Story.joins(:user).where(
   "users.display_name LIKE :term And stories.title LIKE :term", 
   :term =>  "%#{@query}%"
).limit(500).page(params[:page])

如果您想预先加载与故事关联的用户对象:

Story.includes(:user).where(
   "users.display_name LIKE :term And stories.title LIKE :term", 
   :term =>  "%#{@query}%"
).limit(500).page(params[:page])

笔记:

我在 where 子句中使用占位符条件,因为在两个地方使用了相同的查询词。

于 2012-06-20T16:38:02.880 回答