rails:尝试匹配数组中的两个值,获取不支持的参数类型:哈希错误

时间:2019-01-06 18:47:26

标签: database activerecord ruby-on-rails-5 arel ruby-hash

我在两个不同的模型中有两个字段,它们在一个数组中存储位置值,而我试图实现的是一个控制器实例变量,它可以匹配两个数组中的任何相同值,然后在索引视图中显示出来。但是,当我尝试此代码

@submissions = Submission.select(Desired_Location: current_agent.Company_Business_Location)

它会引发此错误:

Unsupported argument type: Hash. Construct an Arel node instead

提交模式:

create_table "submissions", force: :cascade do |t|
t.string "First_Name"
t.string "Last_Name"
t.integer "Phone"
t.string "Email"
t.string "Desired_Location"
t.integer "number_of_beds"
t.integer "number_of_occupants"
t.integer "Rent_price_per_month_gbp"
t.date "Max_move_in_date"
t.string "Tenant_Occupation"
t.string "Contact_me_on"
t.boolean "Furnished"
t.string "Current_Address"
t.text "Property_Requirements"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "location_id"
t.index ["location_id"], name: "index_submissions_on_location_id"
t.index ["user_id"], name: "index_submissions_on_user_id"
 end

代理模式:

create_table "agents", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "Company_Name"
t.string "Company_Email"
t.string "Company_Phone"
t.string "Company_Address"
t.string "Company_Business_Location"
t.string "Contact_Name"
t.string "Contact_Email"
t.string "Contact_Phone"
t.integer "location_id"
t.index ["email"], name: "index_agents_on_email", unique: true
t.index ["location_id"], name: "index_agents_on_location_id"
t.index ["reset_password_token"], name: 
"index_agents_on_reset_password_token", unique: true
 end

在Desired_Location和Company_Business_Location字段中如何存储数据的示例:

["", "Abbey Wood", "Acton", "Anerley", "Angel"]

2 个答案:

答案 0 :(得分:0)

如果Desired_Location是提交模型中的字段名称,请使用以下选择方法。 Select方法不接受哈希作为参数。

您可以传递一个块来检查条件并获得所需的结果。尽管包含所有元素,但在数组上的位置不同时,可以对数组使用sort来使数组相同。

desired_loc_arr = current_agent.Company_Business_Location
@submissions = Submission.select { |sub| sub.Desired_Location.sort == desired_loc_arr.sort }

答案 1 :(得分:0)

要与Rails查询中数组的相同值匹配, 您可以在滑轨中使用ANY of postgres

Submission.where(? = ANY(Desired_Location)", current_agent.Compay_Business_Location)

在这里http://www.postgresqltutorial.com/postgresql-any/

了解更多