【问题标题】:Protector: cannot update id of associated model保护者:无法更新关联模型的 ID
【发布时间】:2013-10-24 13:09:33
【问题描述】:

基本上,这段代码应该允许创建具有所需 url_type 的 url,但是虽然用户可以读取 UrlType,但它不能通过更新操作来设置它。错误是“网址类型无效”

class UrlsController < ApplicationController
  before_filter :authenticate_user!
  before_action :set_url, only: [:show, :edit, :update, :destroy]
  def update
    respond_to do |format|
      if @url.update(url_params)
        format.html { redirect_to @url, notice: 'Url was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @url.errors, status: :unprocessable_entity }
      end
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_url
      @url = Url.restrict!(current_user).find(params[:id])
    end
end

class Url < ActiveRecord::Base
  belongs_to :url_type
   protect do |user|
    if user.admin?
      scope {all}

      can :read
      can :create
      can :update
      can :destroy
    else
      scope {all}
      can :read
      can :create
      can :create, workflow_state: -> (state) { state == 'new'}
      can :update, %w(address contractor_id destination domain url_type_id user_id)
      #cannot :update, 'workflow_state'
    end
  end
end

class UrlType < ActiveRecord::Base
  has_many :urls

  protect do |user|
    if user.admin?
      scope {all}

      can :read
      can :create
      can :update
      can :destroy
    else
      scope {all}
      can :read
      cannot :update
    end
  end
end

示例数据 - url_params 是

 => {"address"=>
 "http://stackoverflow.com/questions/10016195/displaying-errors-when-a-twitter-                    bootstrap-modal-window-contains-a-rails-form-he",
 "user_id"=>1,
 "destination"=>"http://boscogreenholt.org/katelin.pouros",
 "domain"=>"renner.org",
 "url_type_id"=>"1",
 "contractor_id"=>"1"}

【问题讨论】:

    标签: ruby-on-rails-4 protector


    【解决方案1】:

    Protector 无法生成此类错误。这可能意味着您为您的实体分配了accept_nested_attributes,它正是UrlType 的实例无效,而不是url_type_id 的分配。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多