【发布时间】:2015-08-31 12:34:27
【问题描述】:
我有两个模型:商店和用户。用户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:NilClassso 用户在 Shops 中找不到。
当用户选择商店而不只是更新 shop_id 参数时,我如何创建正确的关联?
【问题讨论】:
-
你问的不是很清楚。你能告诉我们目前的方法有什么问题,什么行不通,你到底想做什么......你有什么错误吗?
-
已编辑以包含错误
-
嗯,错误很明显...您确定
params[:id]已分配并匹配现有商店...? -
在客户操作中:
@customers = @shop.users -
哈哈@TheCha͢mp ...我怎么错过了>。undefined method users for Shop class,对吧?
标签: ruby ruby-on-rails-4 associations