I have a controller and two models, a user and a store. A user has_many stores. Inside stores I have a method get_items which lists items. get_items itself needs a reference to the user. What I have done now is the following
我有一个控制器和两个模型,一个用户和一个商店。用户拥有多个商店。在商店内部,我有一个方法get_items列出项目。 get_items本身需要对用户的引用。我现在所做的是以下内容
@items = user.stores.first.get_items(user)
this looks weird to me since the initial caller has to pass itself as an argument to the get_items method. What would you recommend?
这对我来说很奇怪,因为初始调用者必须将自己作为参数传递给get_items方法。你会推荐什么?
best, phil
最好的,菲尔
1 个解决方案
#1
1
If you've defined the relation in two directions,
如果您已在两个方向上定义了关系,
class User < ActiveRecord::Base
has_many :stores
end
class Store < ActiveRecord::Base
belongs_to :user
end
then you have access to the user
that a store belongs to within the Store
instance. So you should be able to write
然后您可以访问Store实例中商店所属的用户。所以你应该能够写作
def get_items
do_something_with user
end
and it should use the correct user. The call to get_items could then be
它应该使用正确的用户。然后可以调用get_items
@items = user.stores.first.get_items
I would personally rename get_items
to items
.
我个人会将get_items重命名为item。
#1
1
If you've defined the relation in two directions,
如果您已在两个方向上定义了关系,
class User < ActiveRecord::Base
has_many :stores
end
class Store < ActiveRecord::Base
belongs_to :user
end
then you have access to the user
that a store belongs to within the Store
instance. So you should be able to write
然后您可以访问Store实例中商店所属的用户。所以你应该能够写作
def get_items
do_something_with user
end
and it should use the correct user. The call to get_items could then be
它应该使用正确的用户。然后可以调用get_items
@items = user.stores.first.get_items
I would personally rename get_items
to items
.
我个人会将get_items重命名为item。