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">
任何帮助将不胜感激
答案 0 :(得分:1)
我认为问题是在视图中使用的变量,对于receiver.id
的情况,您应该使用变量r
而不是f
= f.fields_for :receiver do |r|
= r.text_field :id, value: f.object.receiver.id, class: 'hidden'
也检查在创建反馈时没有传递正确的参数
希望这可以帮助您解决问题。