【问题标题】:Rails 5 nested parameter permitted falseRails 5嵌套参数允许false
【发布时间】:2018-05-03 10:08:24
【问题描述】:

Rails 5 API 嵌套属性允许 false

class TimeSheet < ApplicationRecord 
  has_many :job_times, inverse_of: :time_sheet
  accepts_nested_attributes_for :job_times, :allow_destroy => true 
end

class JobTime < ApplicationRecord
  belongs_to :time_sheet, optional: true
end

控制器

def create
  puts "Job time  #{params.dig(:job_times)}"   
  @time_sheet = TimeSheet.create!(time_sheet_params)

  if @time_sheet.save
    render json: @time_sheet, status: :created, location: @time_sheet
  else
    render json: @time_sheet.errors, status: :unprocessable_entity
  end
end

def time_sheet_params
  params.require(:time_sheet).permit(:first_name, :job_date, 
     job_times_attributes:  [:job_id, :job_department, :job_category, 
         :job_time, :is_overtime ]) 
end

参数:

{"first_name"=>"GG", "job_date"=>"2018-05-22T00:50:19.000Z", "job_times"=>[{"job_id"=>"18001", "job_department"=>"CAD", "job_category"=>"Finishing", "job_time"=>"5", "is_overtime"=>""}, {"job_id"=>"18032", "job_department"=>"test", "job_category"=>"Finishing", "job_time"=>"2", "is_overtime"=>""}], "time_sheet"=>{"first_name"=>"GG", "job_date"=>"2018-05-22T00:50:19.000Z"}}

Job time  [<ActionController::Parameters {"job_id"=>"18001", "job_department"=>"CAD", "job_category"=>"Finishing", "job_time"=>"5", "is_overtime"=>""} permitted: false>, <ActionController::Parameters {"job_id"=>"18032", "job_department"=>"test", "job_category"=>"Finishing", "job_time"=>"2", "is_overtime"=>""} permitted: false>]

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails-5 angular5


    【解决方案1】:

    您的参数命名错误,问题可能出在您的表单视图上。

    您发送的是"job_times" =&gt; [...],但您应该发送的是"job_times_attributes" =&gt; [...]。

    检查您的表单中是否将job_times 字段嵌套在fields_for 助手中。例如,如果form 是您的表单对象,那么您应该执行以下操作:

    <%= form.fields_for :job_times do |subform| %>
    <%= subform.text_field :job_category %>
    <% end %>
    

    或者,如果您要手动生成表单,请使用 job_times_attributes 而不是 job_times

    【讨论】:

    • 谢谢。参数来自 Angular。它来了广告job_times
    • 在这种情况下,您有两个选择: 1. 告诉您的前端 Angular 伙伴您需要它以 job_times_attributes 的形式出现,否则 Rails 的魔法将不起作用。 2. 自己完成将属性映射到正确名称的工作,或者使用给定的属性在模型中创建适当的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多