通过 Rails 关联查询
Querying through a Rails Association
我有两个模型:商店和用户。用户 belong_to
个商店和一个商店 has_many
个用户。用户和商店分别创建,然后用户添加商店,将其 shop_id
更改为 @shop.id
。
我需要@shop.users
查询belong_to
购物的所有用户。我不确定如何实现这一点。目前,唯一的连接是关联,当用户使用此按钮选择商店时,@user.shop_id
会更新到正确的商店:
查看:
<%= link_to 'Add As Your Shop', update_shop_url(id: @user.id, shop_id: @shop.id), class: 'button blue-button', data: { method: 'post' } %>
控制器:
def update_shop
@user = User.find(params[:id])
@shop = Shop.find(params[:shop_id])
@user.update_attributes(shop_id: @shop.id)
flash[:success] = "Added Shop!"
redirect_to @shop
end
这是 ShopsController#Customers 中的查询
def customers
@shop = Shop.find(params[:id])
@customers = Shop.users
end
此查询给出了错误undefined method 'users' for nil:NilClass
因此无法通过商店找到用户。
我如何在用户选择商店时创建正确的关联而不只是更新 shop_id 参数?
您想拥有特定商店的用户,而不是 ("abstract") Shop
模型的关系。因此,在您的示例 @shop
.
中,您必须在商店 实例 上调用 .users
def customers
@shop = Shop.find(params[:id])
@customers = @shop.users
end
你的问题不是很清楚,希望对你有所帮助。另请注意,在您的问题文本中,您实际上询问的是 @shop.users
,但您的代码示例显示为 Shop.users
:)。我认为您实际上有两个问题:How to access all users of a shop ("How to access associated instances?") and "How to assign an object to a belongs_to relation"?
请注意,您的 customers
方法断言可以找到具有该 ID 的商店(否则将抛出错误)。
要设置商店,你可以像这样使用ActiveRecord:
@shop = Shop.find(params[:shop_id])
@user.shop = @shop
我有两个模型:商店和用户。用户 belong_to
个商店和一个商店 has_many
个用户。用户和商店分别创建,然后用户添加商店,将其 shop_id
更改为 @shop.id
。
我需要@shop.users
查询belong_to
购物的所有用户。我不确定如何实现这一点。目前,唯一的连接是关联,当用户使用此按钮选择商店时,@user.shop_id
会更新到正确的商店:
查看:
<%= link_to 'Add As Your Shop', update_shop_url(id: @user.id, shop_id: @shop.id), class: 'button blue-button', data: { method: 'post' } %>
控制器:
def update_shop
@user = User.find(params[:id])
@shop = Shop.find(params[:shop_id])
@user.update_attributes(shop_id: @shop.id)
flash[:success] = "Added Shop!"
redirect_to @shop
end
这是 ShopsController#Customers 中的查询
def customers
@shop = Shop.find(params[:id])
@customers = Shop.users
end
此查询给出了错误undefined method 'users' for nil:NilClass
因此无法通过商店找到用户。
我如何在用户选择商店时创建正确的关联而不只是更新 shop_id 参数?
您想拥有特定商店的用户,而不是 ("abstract") Shop
模型的关系。因此,在您的示例 @shop
.
.users
def customers
@shop = Shop.find(params[:id])
@customers = @shop.users
end
你的问题不是很清楚,希望对你有所帮助。另请注意,在您的问题文本中,您实际上询问的是 @shop.users
,但您的代码示例显示为 Shop.users
:)。我认为您实际上有两个问题:How to access all users of a shop ("How to access associated instances?") and "How to assign an object to a belongs_to relation"?
请注意,您的 customers
方法断言可以找到具有该 ID 的商店(否则将抛出错误)。
要设置商店,你可以像这样使用ActiveRecord:
@shop = Shop.find(params[:shop_id])
@user.shop = @shop