rails 找不到嵌套资源
rails can't find nested resource
Rails 5. 我有一个接受嵌套资源(接收器)的反馈表。
class Feedback < ApplicationRecord
belongs_to :receiver, class_name: 'User', foreign_key: :receiver_id
accepts_nested_attributes_for :receiver
end
class FeedbacksController < ApplicationController
def create
begin
@feedback = Feedback.new feedback_params
rescue Exception => e
binding.pry
end
... do other stuff
end
def feedback_params
params.require(:feedback).permit(:message, receiver_attributes: [:id, :email, :handle])
end
end
end
= f.fields_for :receiver do |r|
= f.text_field :id, value: f.object.receiver.id, class: 'hidden'
我的测试在尝试创建反馈
时失败
#<ActiveRecord::RecordNotFound: Couldn't find User with ID=980191240 for Feedback with ID=>
使用 binding.pry,我可以找到具有测试 ID
的用户
User.find 980191240
#<User id: 980191240, email: "wong.amy@example.com", created_at: "2018-03-27 02:50:52", updated_at: "2018-03-27 02:50:52", first_name: "amy", last_name: "wong", handle: "wong">
任何帮助将不胜感激
我认为问题出在视图上使用的变量,在您的 receiver.id
情况下,您应该使用变量 r
而不是 f
= f.fields_for :receiver do |r|
= r.text_field :id, value: f.object.receiver.id, class: 'hidden'
同时检查在创建反馈时是否传递了正确的参数
希望这能帮助您解决问题。
Rails 5. 我有一个接受嵌套资源(接收器)的反馈表。
class Feedback < ApplicationRecord
belongs_to :receiver, class_name: 'User', foreign_key: :receiver_id
accepts_nested_attributes_for :receiver
end
class FeedbacksController < ApplicationController
def create
begin
@feedback = Feedback.new feedback_params
rescue Exception => e
binding.pry
end
... do other stuff
end
def feedback_params
params.require(:feedback).permit(:message, receiver_attributes: [:id, :email, :handle])
end
end
end
= f.fields_for :receiver do |r|
= f.text_field :id, value: f.object.receiver.id, class: 'hidden'
我的测试在尝试创建反馈
时失败#<ActiveRecord::RecordNotFound: Couldn't find User with ID=980191240 for Feedback with ID=>
使用 binding.pry,我可以找到具有测试 ID
的用户User.find 980191240
#<User id: 980191240, email: "wong.amy@example.com", created_at: "2018-03-27 02:50:52", updated_at: "2018-03-27 02:50:52", first_name: "amy", last_name: "wong", handle: "wong">
任何帮助将不胜感激
我认为问题出在视图上使用的变量,在您的 receiver.id
情况下,您应该使用变量 r
而不是 f
= f.fields_for :receiver do |r|
= r.text_field :id, value: f.object.receiver.id, class: 'hidden'
同时检查在创建反馈时是否传递了正确的参数
希望这能帮助您解决问题。