【问题标题】:Querying through a Rails Association通过 Rails 关联查询
【发布时间】: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


【解决方案1】:

您希望拥有特定商店的用户,而不是(“抽象”)Shop 模型的关系。因此,您必须在商店instance 上调用.users,在您的示例中为@shop

def customers
    @shop = Shop.find(params[:id])
    @customers = @shop.users
end

您的问题并不完全清楚,但我希望这会有所帮助。另请注意,在您的问题文本中,您实际上询问了@shop.users,但您的代码示例显示为Shop.users :)。我认为您实际上有两个问题:如何访问商店的所有用户(“如何访问关联实例?”)和“如何将对象分配给 belongs_to 关系”?

请注意,您的 customers 方法断言可以找到具有该 ID 的商店(否则将引发错误)。

要设置商店,你可以像这样使用 ActiveRecord:

@shop = Shop.find(params[:shop_id])
@user.shop = @shop

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多