Ruby on rails RubyonRails类型错误(can';t将哈希转换为整数)
我在控制器中有一个类作为客户端API,它在不检查组织id的情况下工作,组织id通过用户和成员身份链接到观察Ruby on rails RubyonRails类型错误(can';t将哈希转换为整数),ruby-on-rails,Ruby On Rails,我在控制器中有一个类作为客户端API,它在不检查组织id的情况下工作,组织id通过用户和成员身份链接到观察 def update @observation = Observation.find(params[:id]) if params[:state] == 'submitted' && @observation.submit if @observation.source.source_type == 'registered' @u
def update
@observation = Observation.find(params[:id])
if params[:state] == 'submitted' && @observation.submit
if @observation.source.source_type == 'registered'
@user = User.find(id: @observation.source.source_identifier)
@memberships = Membership.find(user_id: @user.id)
if @memberships.present? &&@memberships.where("organization_id IS NOT NULL")
@observation.approve
end
end
render json: { createdAt: @observation.created_at }, status: 200
else
render nothing: true, status: 406
end
end
TypeError(无法将哈希转换为整数):
app/controllers/api/client/v1/observations\u controller.rb:106:在“更新”中
哪一行是:
@user = User.find(id: @observation.source.source_identifier)
表结构:
# create_table "sources", force: true do |t|
# t.string "device_id"
# t.string "source_type"
# t.string "source_identifier"
# ...
# create_table "users", force: true do |t|
# # t.string "email", default: "", null: false
# t.string "encrypted_password", default: "", null: false
# ...
# t.string "first_name"
# t.string "last_name"
# t.string "phone"
# t.integer "source_id"
# ...
# create_table "memberships", force: true do |t|
# t.integer "user_id"
# t.integer "organization_id"
# t.datetime "verified_at"
# ...
接受一个参数:一个整数
。这应该是您试图查找的记录的ID
执行以下操作,而不是User.find(id:…)
:
@user = User.find(@observation.source.source_identifier)
但是请注意,如果找不到来源,将引发;如果您不想这样做,您可能会希望使用
#find_by_id
,或者相反。假设您运行的是Rails 4+,要按属性查找记录,只需使用以下模式:
Model.find_by(attribute_name: attribute_value)
因此,在你的情况下:
@user = User.find_by(source_identifier: @observation.source.source_identifier)
除非您重写Rails,否则您将尝试使用字符串搜索唯一的表ID,因此这就是错误的来源。奇怪的是,我似乎在文档中的任何地方都找不到它,当我尝试在本地运行它时。你介意提供这方面的消息来源吗?谢谢@Jeremy修复了我的打字错误。文档是。我担心我有一段时间不在循环中了D: