[英]why do i get NoMethodError?
我希望我的交易页面显示用户已添加到购物车中的每个Item
的列表,并且在理解为什么此实现为我带来NoMethodError时遇到了麻烦
因此,在我的TradesController的#show
动作中,我有一个trade_ids
变量,其中包含由$redis.smembers current_user_trade
返回的添加项数组。 然后,我用它对每个项目的ID进行查找,并在我的视图中循环遍历实例变量。
我的交易主管:
class TradesController < ApplicationController
def show
trade_ids = $redis.smembers current_user_trade
@trade_items = Item.find(trade_ids)
end
def add
$redis.sadd current_user_trade, params[:item_id]
render json: current_user.trade_count, status: 200
end
def remove
$redis.srem current_user_trade, params[:item_id]
render json: current_user.trade_count, status: 200
end
private
def current_user_trade
"trade#{current_user.id}"
end
end
这是我用来向current_user_trade
添加项目的方法:
class Item < ActiveRecord::Base
extend FriendlyId
friendly_id :slug, use: [:slugged, :finders]
def slug
[artist.parameterize, title.parameterize].join("-")
end
def trade_action(current_user_id)
if $redis.sismember "trade#{current_user_id}", id
"Remove from"
else
"Add to"
end
end
end
我的路线:
resource :trade, only: [:show] do
put 'add/:item_id', to: 'trades#add', as: :add_to
put 'remove/:item_id', to: 'trades#remove', as: :remove_from
end
在我的交易视图中,我有一个基本的知识:
<% @trade_items.each do |item| %>
<p><%= item.title %></p>
etc
<% end %>
我最初的想法是,这与我一直在使用FriendlyId来生成子弹有关。 但是根据FriendlyId的文档 ,在我的Item模型的slug声明中添加:finders
应该可以通过id重新启用查找。 但事实并非如此。
我也尝试过重构它,以便它使用我的Items:slug,但这也无济于事。
修复。 原来它已被缓存。 我在中途从存储item_id
切换到item_slug
,需要运行redis-cli flushall
来存储和访问正确的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.