Protector: cannot update id of associated model

87 Views Asked by At

Basically, this code should allow creation of url with desired url_type, but although user can read UrlType, it can't set it via update action. The error is 'Url type is invalid'

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

the sample data - url_params is

 => {"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"}
1

There are 1 best solutions below

1
On

Such error can not be generated by Protector. It probably means that you assign your entity with accept_nested_attributes and it is exactly the instance of UrlType that invalidates, not the assignment of url_type_id.