チェックPostgresのドキュメント:[:私、:記号] http://www.postgresql.org/docs/9.2/static/arrays.html
あなたが好きな配列を使用してモデルをインスタンス化することができますまたは["My"、 "Strings"]しかし、それは(私の経験と形ではドキュメント内にあるように)要素を文字列として保存します。私のテストで
[15] pry(main)> Search.create(tokens: [:G, :F])
=> #<Search id: 78, tokens: [:G, :F], created_at: "2013-12-18 06:29:36", updated_at: "2013-12-18 06:29:36">
[16] pry(main)> Search.last
=> #<Search id: 78, tokens: ["G", "F"], created_at: "2013-12-18 06:29:36", updated_at: "2013-12-18 06:29:36">
、私はサーチエンジン、検索、および用語がありますよう
Search.create(tokens: [{hash: 'value'}, {test: "fails"}])
=> TypeError: can't cast Hash to string
。
class SearchEngine < ActiveRecord::Base
has_and_belongs_to_many :terms
has_many :searches, through: :terms
end
class Term < ActiveRecord::Base
has_and_belongs_to_many :searches
has_and_belongs_to_many :searche_engines
end
class Search < ActiveRecord::Base
has_many :rankings
has_many :results, through: :rankings
has_and_belongs_to_many :terms
has_many :search_engines, through :terms
end
# These work:
# these next two are the way postgrespl says to query against the array. You get the
Search.where(tokens: '{A,B}')
Search.where(tokens: '{C,D}').first_or_create
[3] pry(main)> Search.where(tokens: ['C','D']).first
ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: array value must start with "{" or dimension information
[4] pry(main)> Search.where(tokens: '{C,D}').first
=> #<Search id: 77, tokens: ["C", "D"], created_at: "2013-12-18 06:27:24", updated_at: "2013-12-18 06:27:24">
term = "accident"
Search.where("? = ANY (tokens)", term).first
=> #<Search id: 8, tokens: ["accident", "prevention", "safety"], created_at: "2013-12-18 07:48:13", updated_at: "2013-12-18 07:48:13">
Search.create(tokens: [:Aortic, :Any, :Other, :Elements])
Search.where("'Aortic' = ANY (tokens)").first
Parent.first.first_relationships.first.second_.where("'smelly' = ANY (tokens)").first
# The next one will create one with an empty array for tokens and push it into Term.searches anyway. Same thing with 'smelly'
Term.first.searches.where("':smelly' = ANY (tokens)").first_or_create do |s| Term.first.searches << s
end
# These error
Search.where(tokens: "Aortic").first
Search.where(tokens: [:Aortic, :Any, :Other, :Elements]).first
あなたは配列を入れ子になっている場合も、あなたはこれでどこ検索を行うことができます:「{{1,2,3}、{4,5,6}、{7,8,9}} '[1,2,3]、[4,5,6]、[7,8,9]]の行を見つける
実際にネイティブPg配列が必要な場合は、[ActiveRecordPostgresArray]( https://github.com/tlconnor/activerecord-postgres-array)の拡張子。 – dbenhur