开发者

Trouble on finding a class object in a array of classes

I am using Ruby on Rails 3.0.7 and I would like to understand how to handle the following code in order to retrieve a class objects with a specified id.

In my view file I have:

@records = Users.all # This returns an array (class)

In another file, a partial template, I would like to retrieve, for example, the user with id 1, but if I make this:

@records.find(1)

I get an enumerator (class) of all records:

<Enumerator: [<Users id: 1, ... ] >

How can I find the user with id 1 (or other ids) "a là Ruby on Rails Way"?


UPDATE

I use @records = Users.all in a view file because I aim to minimize calls to the database since I need to iterate almost over all records and check them existence. If I do for example:

some_hash.each { |key, value|
  put User.find(v开发者_StackOverflowalue)
}

and I go in the log file, I will see a lot of database requests.


Even though this is probably quite slow, and I suspect there are some less than optimal designs in the app you're working on (not judging, we've all been there), Array#index seems to be what you're looking for:

@records[@records.index{|user| user.id == 1}]

Edit

Although if you need to do something for every user, and you need to access them by id quickly, I'd probably do something like this in your controller. Even if it's not really faster, it's much more readable (to me anyways):

@users_hash = {}
User.all.each{|user| @users_hash[user.id] = user}

Then in your views you can do:

@users_hash[id].username


Use User.scoped instead of User.all. #all will immediately query the database and return an array, whereas #scoped will return an ActiveRecord::Relation object which you can chain further queries. In this case, the database won't be hit until you try and somehow inspect or enumerate the result


Actually you're mistaken. @records.find(1) is returning an object of the class Enumerator (which is not the same as the class Enumerator itself).

The problem here is that, as you've noted, @records is an Array, not an ActiveRecord object, and Array#find (inherited from Enumerable#find--which, when not given a block, returns an object of class Enumerable) is not the same method as ActiveRecord::Base#find (i.e. User#find).

What you should do is, in your controller, pick out the one user record you want:

@user = User.find 1

...and then use @user directly in your template. Generally you should avoid doing ActiveRecord lookups (e.g. find) in your templates. That kind of logic should happen in your controller.


Last time for such case I ended up doing like this:

@assignments = Assignment.find_by_sql(' ... ')

@assignments.find(id: 1).first
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜