【问题标题】:Unpermitted parameters in Rails 5 using has_many, throughRails 5 中使用 has_many 的未经允许的参数,通过
【发布时间】:2023-04-02 03:05:01
【问题描述】:

我的约会模型不断收到未经许可的参数。

这是我的模型

    class Appointment < ApplicationRecord
      belongs_to :client
      belongs_to :trainer
    end

    class Trainer < ApplicationRecord
      has_many :appointments
      has_many :clients, through: :appointments
    end

   class Client < ApplicationRecord
    has_many :appointments
    has_many :trainers, through: :appointments
  end

这是我的控制器,为了简洁起见,我只是列出了我的私有方法。

 def appt_params
    params.require(:appointment).permit(:appointment_date, client_id: [], 
    trainer_id: [])
   end

错误显示培训师、客户的参数未经允许。 我在强参数方法中遗漏了什么吗?

这是我的约会/新视图

<%= form_for @appointment do |f| %>
  <%= f.datetime_select :appointment_date %>
  <%= f.collection_select :trainer, Trainer.all, :id, :first_name %>
  <%= f.collection_select :client, Client.all, :id, :name %>
  <%= f.submit %>
<% end %>

我将集合添加到我的 appt_params 方法中,但仍然遇到相同的错误。我仍然掌握 Rails 的窍门,任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: activerecord ruby-on-rails-5 strong-parameters


    【解决方案1】:

    由于您使用了关联,因此只有 client_id 和 trainer_id 就足够了,它们应该是整数形式而不是数组。

    所以把你的强参数方法代码改成:

    def appt_params
     params.require(:appointment).permit(:appointment_date, :client_id, 
     :trainer_id)
    end
    

    你的应用程序/新视图:

    <%= form_for @appointment do |f| %>
      <%= f.datetime_select :appointment_date %>
      <%= f.collection_select :trainer_id, Trainer.all, :id, :first_name %>
      <%= f.collection_select :client_id, Client.all, :id, :name %>
      <%= f.submit %>
    <% end %>
    

    【讨论】:

    • @ryanb082 很高兴听到这个消息。
    【解决方案2】:

    运行时遇到与您相同的问题,经过数小时的调试,我能够解决它:

    这是我第一次尝试在 Rails 中与与您相似的模型进行关联,因此大多数在线文档建议将外键定义为 client_ids:[] 假设您的 id 是数组,当它们肯定是整数作为我的参数时

    Parameters: {"utf8"=>"✓", "authenticity_token"=>"LEcwQ56xYJGpq2zIs6Cz0YbU7B7mBKRa6rhspVIxo9vEB5/UoFUvHYiN0UC0krTiIp+d0tzhit6DZT1Z8PmYYg==", "califica"=>{"text"=>"hi", "grade"=>"5", "user_id"=>"1", "party_id"=>"1"}, "commit"=>"Create Calification"}
    

    我认为这是由于f.collection_select 采用了预期的一个值。因此,在使用 :user_id =&gt; []user_id:[] 等数组的许可数小时后,我总是收到 Unpermitted parameters 的错误。

    尝试了@Bharath 的答案(这是正确的)但它仍然无法正常工作,那时我意识到我的旧模型没有参考参考(ActiveModel::UnknownAttributeError (unknown attribute 'user_id' for Calification.):)所以我不得不制作一个references migration添加外键,然后一切正常。

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多