简体   繁体   中英

How do i parse an activerecord query to produce collection?

My view code is as below:

<%= b.input :city, as: :select, collection: Lov.where(:remarks => 'lov_city').select('id').select('lov_content'),  placeholder: 'Enter City', label: false %>

When the code is render, the list of data that is shown in my view is #<Lov:0x3241351> ..

Actually the Lov table is a reference table which is not related to any other tables and when i do in the rails console (rails c) and running the same ' Lov.where(:remarks => 'lov_city').select('id').select('lov_content') ' the data is shown but the view is different.

From rails console:

jruby-1.7.16.1 :001 > Lov.where(:remarks => 'lov_city').select('id').select('lov_content')
  lovs Columns (6.0ms)  SHOW FULL COLUMNS FROM `lovs`
  Lov Load (8.0ms)  SELECT id, lov_content FROM `lovs` WHERE `lovs`.`remarks` = 'lov_city'
 => [#<Lov id: 229, lov_content: "Ayer Baloi">, #<Lov id: 230, lov_content: "Ayer Hitam">, #<Lov id: 231, lov_content: "Ayer Tawar 2">, #<Lov id: 232, lov_content: "Ayer Tawar 3">, #<Lov id: 233, lov_content: "Ayer Tawar 4">

如果要获取某些选定的列,请使用pluck

Lov.where(:remarks => 'lov_city').pluck(:id, :lov_content)
Lov.where(:remarks => 'lov_city').select('id').select('lov_content')

This will return an active record object with only an id and lov_content as attribute. I am not sure of what you are trying to display but you need to provide a collection of value instead of an activerecord object.

First of all you can select several attributes at once without having to write several time select such as:

Lov.where(:remarks => 'lov_city').select([:id, :lov_content])

if you need to provide the list of lov_content then you can use this to return an array of lov_content:

Lov.where(:remarks => 'lov_city').collect(&:lov_content)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM