簡體   English   中英

Rails ActiveModel :: ForbiddenAttributesError - ActiveModel ::ForbiddenAttributesErrorвsimple_formnested_fields

[英]Rails ActiveModel::ForbiddenAttributesError - ActiveModel::ForbiddenAttributesError в simple_form nested_fields

我在保存simple_form.fields_for時遇到了麻煩 - 禁用屬性錯誤

預訂控制器中的“創建”操作看起來如此:

    def create
        ...
        new_params = params[:booking]
        new_params[:user_attributes] = new_params[:user_attributes].merge({"password"=>"osmsmsmsm32"}) # password is temp stuff to bypass User save validation
        @booking = Booking.new

        @booking.update(params)
        # however @booking.user.update(params[:booking][:user_attributes]) gives the same error
        ...
    end
    ...

    def booking_params
        params.require(:booking).permit(:arrived_at, :departured_at, :arrival_address, 
              :departure_address, :arrival_city, :departure_city, 
              :reservation_cost, :total_additional_cost, :user_attributes, :user_id, :garage_id, 
               user_attributes: [:id, :name, :surname, :email, :phone], 
               garage_attributes: [:id] 
                                        )
    end
===========================

      Booking:
      belongs_to :user
      accepts_nested_attributes_for :user
===========================

    ##In model User:
      has_many :bookings

但是,具有相同參數的irb控制台中的@booking.user.save & @booking.save可以成功保存並傳遞true,不會出現任何Forbidden Attribute錯誤

這個Forbidden屬性來自哪里? 我確信我允許在表單中發送所有的attrs,我認為我正確地使用accepts_nested_attributes_for,不是嗎?

只需在控制器私有方法中定義您的user_attributes,如下所示:

private
  def user_params
    params.require(
      :user
    ).permit(
        :first_name,
        :last_name,
        :job_title
      )

  end

如果您正在使用嵌套字段,只需在此屬性中添加嵌套屬性,如下所示:

    private
      def user_params
        params.require(
          :user
        ).permit(
            :first_name,
            :last_name,
            :job_title,
            addresses_attributes: [:address_1, :address_2]
          )

      end

通過記住您的模型關聯來編寫嵌套屬性,希望這對您有用。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM