【问题标题】:Rails ActiveModel::ForbiddenAttributesError - ActiveModel::ForbiddenAttributesError в simple_form nested_fieldsRails ActiveModel::ForbiddenAttributesError - ActiveModel::ForbiddenAttributesError в simple_form nested_fields
【发布时间】:2016-11-10 03:32:34
【问题描述】:

保存 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 属性是从哪里来的?我确定我允许我在表单中发送的所有属性,并且我认为我正确使用了accepts_nested_attributes_for,不是吗?

【问题讨论】:

    标签: ruby-on-rails rails-activerecord simple-form nested-attributes activemodel


    【解决方案1】:

    只需在控制器私有方法中定义您的 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
    

    通过考虑您的模型关联来编写嵌套属性, 希望这对你有用。 :)

    【讨论】:

    • 感谢您的回答。然而,它已经这样做了。但令人惊讶的是不起作用,这就是我感到惊讶的原因。
    • 能否请您编写项目的 Rails 版本,并且您正在控制器的新操作中构建用户对象,对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多