Rails after_find回调忽略查询

时间:2014-01-22 05:11:40

标签: ruby-on-rails rails-activerecord

所以,我称之为方法Article.getByTag()

回调after_find工作,但忽略查询(在当前文章中获取所有标签)。

这是rails log

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

1 个答案:

答案 0 :(得分:0)

基本上,这就是你所需要的:

文章类:

class Article < ActiveRecord::Base
  has_many :tags_to_articles
  has_many :tags, through: :tags_to_articles 
end

和连接表的模型类

class TagsToArticle < ActiveRecord::Base
  belongs_to :article
  belongs_to :tag
end

然后按照标记名称获取所有文章:

Article.joins(:tags).where('tags.name' => tag_name)

我正在写这篇文章,我已经没有想到你在代码中实现了什么,所以如果代码从一开始就不起作用,请原谅我 - 玩用它和使工作。

另外,我建议开始一个新的教程项目,你在那里重新发明了很多轮子(注意你不需要after_find钩子,因为has_many :tags, through: :tags_to_articles为你做了这个)并做了很多搞笑东西(比如命名一个与它引用的类同名的类的属性),你会沮丧地烧掉自己。

另外,如果您使用rails 4,则不需要进行attr_accessible舞蹈,如果不这样做,我建议您查看strong_parameters gem https://github.com/rails/strong_parameters

请参阅:http://guides.rubyonrails.org/association_basics.html

并采取特别注释的命名公约 - 单数和复数,camelcase和匈牙利表示法,大写和小写,它们都有自己的位置和意义,教程通常可以很好地指导你完成它

Ruby和Rails非常漂亮且功能强大,但前提是你让它们。如果您仍在基本上编写Java,那么语言中没有固有的好处会以某种方式注入您的代码。