檢查Postgres的這個文檔:http://www.postgresql.org/docs/9.2/static/arrays.html
可以使用像數組實例化一個模型[:我,:符號]或[「我的」,「字符串」],但它(在我的經驗,並形成什麼,似乎在docs)將保存元素的字符串。
Search.create(tokens: [{hash: 'value'}, {test: "fails"}])
=> TypeError: can't cast Hash to string
凡爲:
[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">
在我的測試中,我有一個的搜索引擎,搜索和期限。
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 2012-03-19 04:31:29