所以,我打電話給方法Article.getByTag()
。Rails after_find回調忽略查詢
回調after_find的工作,但忽略查詢(其中獲取當前文章的所有標籤)。
它的軌道記錄
Started GET "/article/lorem" for 127.0.0.1 at 2014-01-22 08:51:11 +0400
Processing by ArticleController#show_tag as HTML
Parameters: {"tagname"=>"lorem"}
Tags Load (0.2ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`name` = 'lorem' LIMIT 1
Article Load (0.1ms) SELECT `articles`.* FROM `articles` INNER JOIN `tag2articles` ON `tag2articles`.`article_id` = `articles`.`id` WHERE `tag2articles`.`Tags_id` = 5
start set article tags for article 3
getTags by article 3
end set article tags
第三類:
class Article < ActiveRecord::Base
attr_accessible :text, :title
attr_accessor :tags
has_many :tag2articles
after_find do |article|
logger.info 'start set article tags for article '+article.id.to_s
article.tags = Tag2article.getTags(article.id)
logger.info 'end set article tags'
end
def self.getByTag(tagname)
@tag = Tags.get(tagname)
Article.joins(:tag2articles).where('tag2articles.Tags_id' => @tag[:id]).all()
end
end
和類Tag2article
class Tag2article < ActiveRecord::Base
belongs_to :Article
belongs_to :Tags
attr_accessible :Article, :Tags
def self.getTags(article)
logger.info 'getTags by article '+article.to_s
@tags = Tag2article.joins(:Tags).where(:Article_id => article).select('tags.*')
return @tags
end
def self.getArticle(tag)
Tag2article.where(:Tags_id => tag).joins(:Article).select('articles.*')
end
end
「標籤」模型類在哪裏?它是如何實現的? – Surya