我是铁杆和红宝石的新手.
我在用户和商店之间有一个has_many关联
以下是我的工作:
@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">]
Run Code Online (Sandbox Code Playgroud)
所以基本上我首先验证用户,然后获取用户所属的所有商店.为此,我得到了一份清单.在哈希列表中,我想知道是否有任何内容store_id == 4.
我按顺序做:
@user.stores.first.store_id==4
false
@user.stores.second.store_id==4
false
Run Code Online (Sandbox Code Playgroud)
我怎么能在循环中做到这一点?有没有更好的方法来做到这一点.
欢迎来到Rails,
这里你最好的方法可能不是使用循环,而是将查找链接到你的第一个查找器.
例如:
@user.stores.find(store_id)
这将利用数据库并且速度更快.
查看API
如果你想循环,你可以做类似以下的事情
@user.stores.each do |store|
@my_store = store if store.id == store_id
end
Run Code Online (Sandbox Code Playgroud)
要么
@my_store = @user.stores.select{|s| s.id == store_id}
要么
@contains_store = @user.stores.include?{|s| s.id == store_id}
祝好运,