创建操作-ActiveModel :: ForbiddenAttributesError

问题描述 投票:0回答:2

我正在尝试创建与current user相关的诊所。但是当我点击提交时,我得到了这个错误。我正在使用devise,rails admin和cancancan。我不知道这些错误是否可能导致错误,或其他错误。

ActiveModel :: ForbiddenAttributesError in ClinicsController#createActiveModel :: ForbiddenAttributesError

user.rb

class User < ApplicationRecord

  has_many :clinics, dependent: :destroy
  accepts_nested_attributes_for :clinics, reject_if: :all_blank, allow_destroy: true

end

clinic.rb

class Clinic < ApplicationRecord  

    belongs_to :user   

end

clinics_controller.rb

class ClinicsController < ApplicationController
    before_action :set_clinic, only: [:show, :edit, :update, :destroy]

    def index
        @clinic = Clinic.all      
        @user = current_user
     end

     def show
        @clinic = Clinic.find(params[:id])
        @user = current_user
     end

     def edit
        @clinic = Clinic.find(params[:id])
     end


    def new
        @clinic = current_user.clinics.new
    end

    def create
        @clinic = current_user.clinics.new(params[:clinic])

        respond_to do |format|
          if @clinic.save
            format.html { redirect_to @clinic, notice: 'Clinic was successfully created.' }
            format.json { render :show, status: :created, location: @clinic }
          else
            format.html { render :new }
            format.json { render json: @clinic.errors, status: :unprocessable_entity }
          end
        end
      end


      def update
        respond_to do |format|
          if @clinic.update(params[:clinic])
            format.html { redirect_to @clinic, notice: 'Clinic was successfully updated.' }
            format.json { render :show, status: :ok, location: @clinic }
          else
            format.html { render :edit }
            format.json { render json: @clinic.errors, status: :unprocessable_entity }
          end
        end
      end



  def destroy
    @clinic.destroy
    respond_to do |format|
      format.html { redirect_to clinics_url, notice: 'Clinic was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_clinic
      @clinic = Clinic.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user)
      .permit(:first_name, :last_name, :email, :password, :password_confirmation, :phone, 
        :practitioner_image,  
        :clinic_logo,
        clinic_images: [],
        profession_ids: [], 
        speciality_ids: [], 
        services_attributes: [:id, :description, :name, :duration, :price, :_destroy], 
        educations_attributes: [:id, :name, :place, :year, :_destroy],
        membership_ids: [],
        awards_attributes: [:id, :name, :year, :_destroy],
        clinics_attributes: [:id, :user_id, :clinic_name, :clinic_address, :clinic_zip_code, :clinic_municipality, :clinic_about, :clinic_mail, :clinic_phone, :clinic_website, :clinic_city, :_destroy,
        practitioners_attributes: [:id, :public_health_insurance, :practitioner_gender, :practitioner_first_name, :practitioner_last_name, :practitioner_description, :practitioner_mail, :practitioner_phone, :practitioner_website, :_destroy]])

    end
end

new.html.erb

<div id="ClinicGenerel" class="TabBlock">
  <div class="content">
    <div class="content clinic">
      <h2 class="page-title">Generel information</h2>
      <%= simple_form_for [@clinic] do |f| %>
        <%= render 'clinics_fields', :f => f %>
        <div class="submit-container">
          <%= f.submit "Gem", :class => 'btn blue'  %>
        </div>
      <% end %>
    </div>
  </div>
</div>

Log

Started POST "/clinics" for ::1 at 2020-03-09 20:35:16 +0100
Processing by ClinicsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"lkftNxR96kkoI4+m00fSevQC+dZU9KsqhvWrcWg+7RPNWd593lPj2aWBdM2vfX83k4t2WUb2LODPFJVnFwJkZg==", "clinic"=>{"clinic_name"=>"Testin", "clinic_address"=>"add", "clinic_zip_code"=>"34334", "clinic_city"=>"adsd", "clinic_municipality"=>"sadsa", "clinic_about"=>"dasds", "clinic_mail"=>"[email protected]", "clinic_phone"=>"24210566", "clinic_website"=>""}, "commit"=>"Gem"}
  User Load (0.8ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 96 ORDER BY `users`.`id` ASC LIMIT 1
  ↳ app/controllers/clinics_controller.rb:25
Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.8ms)



ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):

app/controllers/clinics_controller.rb:25:in `create'
ruby-on-rails attributes nested-attributes
2个回答
0
投票

将您的new.html.erb更改为

<div id="ClinicGenerel" class="TabBlock">
  <div class="content">
    <div class="content clinic">
      <h2 class="page-title">Generel information</h2>
      <%= simple_form_for [@clinic] do |f| %>
        <%= render 'clinics_fields', :f => f %>
        <div class="submit-container">
          <%= f.submit "Gem", :class => 'btn blue'  %>
        </div>
      <% end %>
    </div>
  </div>
</div>

然后重试。需要删除<%= f.simple_fields_for(:clinics) do |p| %>,因为<%= f.simple_fields_for(:clinics) do |p| %>会尝试循环遍历clinicsassociation clinic,但不存在。


0
投票

从您共享的代码库中,您似乎对如何在单个请求中创建嵌套关系感到困惑。也就是说,在上述情况下,您可以按单个请求在单个请求中创建用户和诊所。

有几种解决方案可以使其正常工作。

  1. 参考正确的参数

Parameters: {"utf8"=>"✓", "authenticity_token"=>"1MpJgYCodgCLbJI2i5pZEjAV/a0qvJRHuLaSaim9Y3byHDAAqa4IbogbJNEzPTpyDNMRM3Wz5UFRU00CcBOYBQ==", "clinic"=>{"clinics"=>{"clinic_name"=>"My clinic", "clinic_address"=>"sdd", "clinic_zip_code"=>"343443", "clinic_city"=>"sadsasa", "clinic_municipality"=>"dsd", "clinic_about"=>"sasd", "clinic_mail"=>"[email protected]", "clinic_phone"=>"24210866", "clinic_website"=>""}}, "commit"=>"Gem"}

[如果您查看日志,则找不到任何键clinics_attributes,但是您试图通过params[:clinics_attributes]操作中的create进行操作,该操作将返回nil

快速修复:在params[:clinics_attributes]操作中将params[:clinic][:clinics]替换为create

  1. 更好的版本是@ sahil-grover在上面的答案中建议的内容。

但是您仍然必须了解参数的结构并调整访问方式。

进行此更改后,您需要在params[:clinics_attributes]操作中将params[:clinic]替换为create

  1. 解决方案2更好的版本是使用强参数(在您的情况下为user_params
© www.soinside.com 2019 - 2024. All rights reserved.