当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby - selecting certain users in rails

问题描述:

I'm writing a zombie survival app, and I'm trying to select all my users marked "alive" where :alive is a boolean.

I was writing a private method in my users controller but can't get the ruby right, does anyone have a pointer?

 def get_alive

@holder = (User.map {|user| user})

@user = @holder.each {|i| if i.alive @user << i}

end

thanks

网友答案:

Use a scope to find all alive users.

class User < ActiveRecord::Base
  scope :alive, where(:alive => true)
  # ... the rest of your model ...
end

Then you can do this:

@alive_users = User.alive
网友答案:

You could just select those users directly if User is active record:

User.where(:alive => true)

Or filter for just those users:

User.all.filter(&:alive)
网友答案:

you need to give a bit more details what "holder" is supposed to be... and why you are comparing against 'i'

otherwise:

User.where(:alive => true)

it's a good idea to wrap this in a scope as in Sean Hill's answer

网友答案:

You can even use this syntax in where query

User.where(alive: true)

Or use select over array of object. But select is slow

User.all.select{ |user| user.alive == true}
分享给朋友:
您可能感兴趣的文章:
随机阅读: