Cameron Cameron - 1 month ago 9
Ruby Question

Getting invalid value for Integer() in rails

I have the following table in my Rails app that contains Permissions:

id: INTEGER, name: TEXT, controller: TEXT, action: TEXT, description: TEXT, created_at: TEXT, updated_at: TEXT


And I want to write or update to it all of the controller actions in my application so that they can be used against roles/users in
CanCanCan
.

This is achieved by hitting the
build
method in my
PermissionsController


def build
write_permission("all", "manage", "Everything", "All operations", true)
ApplicationController.subclasses.each do |controller|
if controller.respond_to?(:permission)
controller_class, description = controller.permission
write_permission(controller_class, "manage", description, "All operations")
controller.action_methods.each do |action|
if action.to_s.index("_callback").nil?
action_desc, cancan_action = eval_cancan_action(action)
write_permission(controller_class, cancan_action, description, action_desc)
end
end
end
end
end


So the idea is that it loops through all the controllers and actions and then call calls
write_permission
to add or update the DB.

protected

def eval_cancan_action(action)
case action.to_s
when "index", "show", "search"
cancan_action = "read"
action_desc = I18n.t :read
when "create", "new"
cancan_action = "create"
action_desc = I18n.t :create
when "edit", "update"
cancan_action = "update"
action_desc = I18n.t :edit
when "delete", "destroy"
cancan_action = "delete"
action_desc = I18n.t :delete
else
cancan_action = action.to_s
action_desc = "Other: " << cancan_action
end
return action_desc, cancan_action
end

def write_permission(controller, cancan_action, name, description, force_id_1 = false)
permission = Permission.first(:conditions => ["controller = ? and action = ?", controller, cancan_action])
if not permission
permission = Permission.new
permission.id = 1 if force_id_1
permission.controller = controller
permission.action = cancan_action
permission.name = name
permission.description = description
permission.save
else
permission.name = name
permission.description = description
permission.save
end
end


However I get this error:

invalid value for Integer(): "{:conditions=>[\"controller = ? and action = ?\""


I can't understand what the issue is, as the only INTEGER is the id.

But we're not finding the first Permission using id...

Answer

I think the issue is with the way you are using the first method on Permission. See the documentation: http://apidock.com/rails/ActiveRecord/FinderMethods/first

You could write it this way instead:

Permission.where(controller: controller, action: cancan_action).first