how to loop through a collection and find something in rails
I am new to rails and ruby.
I have a has_many association between user and store
below is what I do:
@user = User.find_by_userid_and_password("someuser", "12345")
=> #<User id: 1, userid: "someuser", password: "12345",
created_at: "2010-01-25 00:00:00", updated_at: "2010-01-25 00:00:00">
@user.stores
=> [#<Store id: 3, store_id: 3, store_name: "New Store 2",
created_at: "2010-01-25 00:00:00", updated_at: "2010-01-25 00:00:00">,
#<Store id: 5, store_id: 5, store_name: "Store 14th and M",
created_at: "2010-01-25 00:00:00", updated_at: "2010-01-25 00:00:开发者_开发知识库00">]
so basically i am first authenticating the user and then getting all the stores that a user belongs to. For that I get a list back. In that list of hashes i want to find out if anything is there with store_id == 4
.
sequentially I do:
@user.stores.first.store_id==4
false
@user.stores.second.store_id==4
false
how can i make this in a loop? and is there any better way to do this.
Welcome to Rails,
Your best approach here is probably not to use a loop, but to chain a find to your first finder.
For example:
@user.stores.find(store_id)
This will leverage the db and be much faster.
Check out the API
If you do want to loop you do something like the following
@user.stores.each do |store|
@my_store = store if store.id == store_id
end
or
@my_store = @user.stores.select{|s| s.id == store_id}
or
@contains_store = @user.stores.include?{|s| s.id == store_id}
Good luck,
精彩评论