[英]Undefined method on create with has_many and belongs_to relationship
[英]Rails Undefined Method for Has_Many/Belongs_To Relationship
我有一个应用程序,管理员必须在该应用程序中为每个用户创建自定义价格,然后他们才能购买产品。 一个pricing
belongs_to
一个user
和一个product
,一个user
has_many
pricings
和product
has_many
pricings
。 路线是这样的:
devise_for :users, :controllers => { registrations: 'registrations' }
resources :users, only: [:show]
resources :products do
resources :pricings
end
在users#show
页面,我试图让列表pricings
该用户。 我的users_controller
有以下内容:
def show
@user = User.find(params[:id])
@products_with_pricing = Product.joins(:pricings).group("products.id").having("count(products.id) > ?",0)
end
这在我的users#show
视图上:
<% @products_with_pricing.each do |product| %>
<% if product.pricing.user == current_user %>
<%= product.name %>
<% end %>
<% end %>
如果我省略if ....== current_user
语句,这将显示所有pricings
所有产品名称,但是使用该语句,我在if语句行上看到NoMethod
错误,该错误是:
#的未定义方法“定价”是什么意思? pricings`
谁能让我直截了当地实现此目标的最佳方法?
产品has_许多定价
这意味着要获取产品的价格,您需要调用product.pricings
,这将返回价格的集合。 您看到的错误是正确的,产品没有一种pricing
方法可以返回一个定价对象,而是有一种pricings
方法可以返回许多定价。
如果您的目标是仅获取价格也属于用户的产品,则建议您调整SQL查询以完成此操作
Product.joins(pricings: :users)
.where(pricings: { user: { id: current_user.id } })
.group("products.id")
.having("count(products.id) > ?",0)
注意:您可能需要弄混多个定价和用户在哪里加入
该查询引入了一个新的联接和一个where子句,该子句将过滤定价为具有当前用户ID的用户的产品,因此您根本不需要if语句
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.