Ruby on rails TypeError (cannot use hash for integer)

I have a class in controller as a client API, it works without checking organization_id, organization_id is related to observing via user and membership.

 def update
    @observation = Observation.find(params[:id])
    if params[:state] == 'submitted' && @observation.submit
      if @observation.source.source_type == 'registered'
        @user = User.find(id: @observation.source.source_identifier)
        @memberships = Membership.find(user_id: @user.id)
        if @memberships.present? &&@memberships.where("organization_id IS NOT NULL")
          @observation.approve
        end
      end

      render json: { createdAt: @observation.created_at }, status: 200
    else
      render nothing: true, status: 406
    end
  end

      

TypeError (cannot use hash for integer): app / controllers / api / client / v1 / observ_controller.rb: 106: in `update 'which is the line:

@user = User.find(id: @observation.source.source_identifier)

      

Table structure:

  # create_table "sources", force: true do |t|
  #   t.string   "device_id"
  #   t.string   "source_type"
  #   t.string   "source_identifier"
  #   ...

  # create_table "users", force: true do |t|
  #     #   t.string   "email",                  default: "", null: false
  #   t.string   "encrypted_password",     default: "", null: false
  #    ...
  #   t.string   "first_name"
  #   t.string   "last_name"
  #   t.string   "phone"
  #   t.integer  "source_id"
  #   ...

  # create_table "memberships", force: true do |t|
  #   t.integer  "user_id"
  #   t.integer  "organization_id"
  #   t.datetime "verified_at"
  #   ...

      

+3


source to share


2 answers


ActiveRecord::Base#find

takes one argument: a Integer

. This should be the ID of the post you are trying to find.

User.find(id: ...)

Do the following instead :



@user = User.find(@observation.source.source_identifier)

      

Note, however, that it #find

will go up if it cannot find the source; if you don't want to, chances are you will want to use #find_by_id

or where(id: ...).first

.

+2


source


Assuming you are using Rails 4+ to find a record by attribute, just use this pattern:

Model.find_by(attribute_name: attribute_value)

      



So in your case:

@user = User.find_by(source_identifier: @observation.source.source_identifier)

      

+3


source







All Articles