如何将此attr_writer属性转换为实际的数据库列?

时间:2012-03-11 14:15:31

标签: ruby-on-rails

我有 Post 模型:

class Post < ActiveRecord::Base
  attr_accessible :title, :content, :tag_names
  has_many :taggings, :dependent => :destroy
  has_many :tags, :through => :taggings

  attr_writer :tag_names
  after_save :assign_tags
  before_create :init_sort_column

  def tag_names
    @tag_names || tags.map(&:name).join(" ")
  end

  private

  def assign_tags
    self.tags = []
    return if @tag_names.blank?
    @tag_names.split(" ").each do |name|
      tag = Tag.find_or_create_by_name(name)
      self.tags << tag unless tags.include?(tag)
    end
  end

  def init_sort_column
    self.content_changed_at = self.created_at || Time.now
  end
end

标记模型:

class Tag < ActiveRecord::Base
  has_many :taggings, :dependent => :destroy  
  has_many :posts, :through => :taggings
  has_many :subscriptions
  has_many :subscribed_users, :source => :user, :through => :subscriptions

  def tag_posts_count
    "#{self.name} (#{self.posts.count})"
  end
end

我想将attr_writer :tag_names转换为数据库中的实际列,以便我可以执行此操作:Post.find_by_tag_names("drinks")

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

你怎么看待转变协会?

Tag.find_by_name('drinks').posts

你应该存档相同的。