Rails,带有逗号的单个单元格中的关联ID(另一个表中的行数不多)

时间:2015-06-15 10:58:01

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord rails-activerecord

我跟随这个伟大的演员:

http://railscasts.com/episodes/258-token-fields-revised

我的数据库是 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}%")
    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

authorship.rb

class Authorship < ActiveRecord::Base
  belongs_to :book
  belongs_to :author
end

book.rb

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

但我不想创建&#34; authorship&#34; 表,因为有很多行!我只想在书的表中添加一个包含作者ID的列(字符串),如下所示:

图书表

    id    |    name    |    author_ids    
-------------------------------------------
     1    |   Book A   |  15,12,16,19,2
     2    |   Book B   |  1,2,5,44,159,3

这可能吗?

0 个答案:

没有答案