Ruby on rails TypeError(无法将Hash强制转换为整数)

时间:2015-07-27 23:54:19

标签: ruby-on-rails

我在控制器中有一个类作为客户端API,它在没有检查organization_id的情况下工作,organization_id与通过用户和成员资格的观察相关联。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#0f0"
        android:layout_centerVertical="true"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher"
            android:background="#f00"/>

        <View
            android:id="@+id/rippleView"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:background="#00f"
            android:layout_gravity="center"
            />
    </FrameLayout>
</RelativeLayout>

TypeError(无法将哈希转换为整数):   app / controllers / api / client / v1 / observation_controller.rb:106:在`update'中 这是行:

 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

表格结构:

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

2 个答案:

答案 0 :(得分:3)

假设您正在运行Rails 4+,要按属性查找记录,只需使用此模式:

Model.find_by(attribute_name: attribute_value)

所以,在你的情况下:

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

答案 1 :(得分:2)

ActiveRecord::Base#find有一个参数:Integer。这应该是您尝试查找的记录的ID。

而不是User.find(id: ...),请执行以下操作:

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

但请注意,#find 如果无法找到来源,会加注;如果你不想这样,你可能会想要使用#find_by_idwhere(id: ...).first