简体   繁体   中英

Can't access data in ActiveHash

I'm using the Gem active_hash https://github.com/zilkey/active_hash to create models for simple data that I don't want to create DB tables for.

For example, I have this model setup for FieldTypes:

class FieldType < ActiveHash::Base
  self.data = [
      {:id => 1, :name => "text", :friendly_name => "Text"},
      {:id => 2, :name => "textarea", :friendly_ => "Text Area"},
      {:id => 3, :name => "image", :friendly_ => "Image"},
  ]
end

And I'm trying to list these field types for a select:

def field_types_for_select
  #FieldType.all.order('name asc').collect { |t| [t.friendly_name, t.name] }
  FieldType.pluck(:friendly_name, :name)
end

But I get an error that order, collect or pluck are not defined.

How do I access this data? This works fine on other models, just not ActiveHash ones. According to the docs the model should work the same as ActiveRecord but I don't seem to be able to access it the same. FieldType.all works, but other methods do not.

Pluck isn't defined on ActiveHash::Base . It is defined on ActiveRecord::Relation::Calculations , and it's purpose is to produce a SQL select for the columns you specify. You will not be able to get it to work with ActiveHash .

You can, however, define your own pluck on your FieldType model.

def self.pluck(*columns)
  data.map { |row| row.values_at(*columns) }
end

Or query the data directly:

FiledType.data.map { |row| row.values_at(:friendly_name, :name) }

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