Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails TypeError (can't cast Hash to integer)

I have a class in the controller as a client API, it was working without checking organization_id, organization_id is linked to observation through user and memberships.

 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 (can't cast Hash to integer): app/controllers/api/client/v1/observations_controller.rb:106:in `update' which is 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"
  #   ...
like image 421
MangooSaSa Avatar asked Dec 21 '25 21:12

MangooSaSa


1 Answers

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

Model.find_by(attribute_name: attribute_value)

So, in your case:

@user = User.find_by(source_identifier: @observation.source.source_identifier)
like image 59
steve klein Avatar answered Dec 23 '25 12:12

steve klein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!