2015-11-25 89 views
0

我有点卡住了,任何帮助或建议将不胜感激。Rails 4 - 使用'where'来搜索和显示特定用户

我想只显示有简历的用户,但我不确定如何 - 我在我的文件中有以下编码 - 您的建议&帮助将不胜感激。

在我的用户/ index.html的

<% users.each do |user| %> 
    <%= user.resume.summary %> 
<% end %> 

模式

create_table "resumes", force: true do |t| 
    t.text  "summary" 
    t.integer "user_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 

车型

user.rb 
has_one :resume 

resume.rb 
belongs_to :user 

我想这样做,只显示用户简历的搜索。 我想下面的,但没有运气

<% users.where(resume_id: !nil).each do |user| %> 
    <%= user.resume.summary %> 
<% end %> 

<% users.where("resume IS NOT NULL != ?", "").each do |user| %> 
    <%= user.resume.summary %> 
<% end %> 

我试着写一个范围,但没有运气

user.rb file 
scope :users_with_resumes, -> {where(['resume != ?', nil])} 

users/index.html.erb file 
<% @users.users_with_resumes.each do |userj| %> 
    <%= user.resume.summary %> 
<% end %> 

回答

2

你靠近正中目标,但你在你的努力语法稍微偏离:

# This won't work because you're now searching for the value !nil (or 'true') 
<% users.where(resume_id: !nil).each do |user| %> 
    <%= user.resume.summary %> 
<% end %> 

# This is a double negative, syntactically incorrect, and referencing resume instead of resume_id 
<% users.where("resume IS NOT NULL != ?", "").each do |user| %> 
    <%= user.resume.summary %> 
<% end %> 

你应该使用下列之一:

users.where.not(resume_id: nil) 

users.where("resume_id IS NOT NULL") 

我想你会发现这些陈述中的任何一个都可以满足你的目的,无论是否有范围或其他。

+0

感谢你洙多! @ConnorCMckee – ARTLoe

0

以下代码仅显示与简历

用户协会

user has_one resume 
resume belongs_to user 

架构

create_table "resumes", force: true do |t| 
    t.text  "summary" 
    t.integer "user_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 

user.rb

scope :users_with_resumes, -> {where("id in (select user_id from resumes)")} 

or instead of a scope you can write a method 

def self.users_with_resumes 
where("id in (select user_id from resumes)") 
end 

用户/ index.html.erb [该显示器仅简历的用户]

<% @users.users_with_resumes.each do |user| %> 
<%= user.resume.summary %> 
<% end %> 
相关问题