【发布时间】:2020-05-13 15:20:00
【问题描述】:
我想创建一个方法badges#show,例如在StackOverFlow 中完成,其中显示所选徽章和获得它的用户。我创建了一个BadgesController,其中包含以下内容:
# Find badge
before_action :set_badge, only: %i[show]
# GET /badges/1
def show; end
private
# Set badge
def set_badge
@badge = Merit::Badge.find(params[:badge_id])
end
在merit.rb(我只显示下面第一个徽章的代码):
# Use this hook to configure merit parameters
Merit.setup do |config|
# Check rules on each request or in background
# config.checks_on_each_request = true
# Define ORM. Could be :active_record (default) and :mongoid
# config.orm = :active_record
# Add application observers to get notifications when reputation changes.
# config.add_observer 'MyObserverClassName'
# Define :user_model_name. This model will be used to grand badge if no
# `:to` option is given. Default is 'User'.
# config.user_model_name = 'User'
# Define :current_user_method. Similar to previous option. It will be used
# to retrieve :user_model_name object if no `:to` option is given. Default
# is "current_#{user_model_name.downcase}".
# config.current_user_method = 'current_user'
end
Merit::Badge.create!(
id: 1,
name: 'just-registered',
description: 'New member',
custom_fields: {
icon_tag: 'user',
category: 'user'
}
)
# More badges [...]
但是,当我尝试通过 <%= @badge.name %> 显示徽章名称时,我得到以下信息:
undefined method 'name' for #<#<Class:0x000000001290cc18>:0x000000000c8c9d10>.
我在调用 badges#show 方法时传递的 params 是 1 (在网址中: /badges/1)。
以下行抛出相同的错误:
@badge = Merit::Badge.find_by_id(params[:badge_id])@badge = Merit::Badge.find_by_id(params[:id])@badge = Merit::Badge.find(params[:id])
如果我将@badge = Merit::Badge.find(params[:badge_id]) 更改为@badge = Merit::Badge.find(:id),我会得到:Could not find Merit::Badge with key "id"。
当我尝试调试我的代码时,视图中的<%= debug @badge %> 会发生以下情况(@badge = Merit::Badge.find(params[:badge_id])):
#<#<Class:0x000000000da762c0>:0x000000000af48a80 @keys=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49], @mapper=#<Ambry::Mapper:0x000000000af48f58 @klass=Merit::Badge(id, name, level, description, custom_fields), @adapter_name=:main, @indexes={}, @lock=#<Thread::Mutex:0x000000000af48d28>, @options={}, @hash={1=>{:id=>1, :name=>"just-registered", :level=>nil, :description=>"New member", :custom_fields=>{:icon_tag=>"user", :category=>"user"}} [...]
它显示了一个带有我在初始化文件merit.rb 中的所有标记的哈希。我不明白为什么控制器没有传递 id 参数。
<%= @badge.find(1).name %> 在视图中工作正常。
我做错了什么?
提前谢谢你!
【问题讨论】:
-
试试这个:@badge = Merit::Badge.find(params[:id])
-
@nattfodd 我明白了
Could not find Merit::Badge with key "1"。我确实有一个 id=1 的徽章。 -
徽章使用 ambry,因此语法可能与 ActiveRecord 不同。见github.com/norman/ambry。你可以使用
find_by_id:github.com/merit-gem/merit/blob/master/app/models/merit/… -
@TuteC 我写了以下几行:
@badge = Merit::Badge.find_by_id(params[:badge_id])&@badge = Merit::Badge.find_by_id(params[:id])两者仍然抛出与前面提到的相同的错误。 -
@TuteC 在没有
params的情况下编写我之前的 cmets 中提到的行会引发相同的错误。
标签: ruby-on-rails ruby badge merit-gem