Ruby on rails Rails、单个单元格中的关联ID和逗号(另一个表中的行不多)
我正在关注这个伟大的演员阵容: 我的数据库是Postgres 此模式: author.rbRuby on rails Rails、单个单元格中的关联ID和逗号(另一个表中的行不多),ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord,Ruby On Rails,Ruby,Ruby On Rails 4,Activerecord,Rails Activerecord,我正在关注这个伟大的演员阵容: 我的数据库是Postgres 此模式: author.rb class Author < ActiveRecord::Base attr_accessible :name has_many :authorships has_many :books, through: :authorships def self.tokens(query) authors = where("name like ?", "%#{query}%")
class Author < ActiveRecord::Base
attr_accessible :name
has_many :authorships
has_many :books, through: :authorships
def self.tokens(query)
authors = where("name like ?", "%#{query}%")
if authors.empty?
[{id: "<<<#{query}>>>", name: "New: \"#{query}\""}]
else
authors
end
end
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
tokens.split(',')
end
end
class Authorship < ActiveRecord::Base
belongs_to :book
belongs_to :author
end
class Book < ActiveRecord::Base
attr_accessible :name, :author_tokens
has_many :authorships
has_many :authors, through: :authorships
attr_reader :author_tokens
def author_tokens=(tokens)
self.author_ids = Author.ids_from_tokens(tokens)
end
end
这可能吗?您正在运行的数据库客户端是什么?Postgresql。这重要吗?我可以使用postgre的特定数组功能吗?为什么要避免使用
作者身份表?它非常方便,而且一张桌子应该有很多行。数据库能够处理数以百万计的条目。因为我认为单元格中的数组很有用,而不是一个有数千行的沉重表!我错了?这当然是可能的,但既没有用处也没有灵活性。假设您想添加一个属性,例如作者是一本书的合著者。无法将其添加到单元格中。
id | name | author_ids
-------------------------------------------
1 | Book A | 15,12,16,19,2
2 | Book B | 1,2,5,44,159,3