2014-01-22 35 views
0

所以,我打电话给方法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 
+0

“标签”模型类在哪里?它是如何实现的? – Surya

回答

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为你做这个),并做了很多有趣的东西(如命名属性的一个班级与其引用的班级名称相同),那么你只会在挫折中燃烧自己。

另外,如果你使用的轨道4,你不需要做attr_accessible舞蹈,如果你不这样做,我建议在strong_parameters宝石考虑看看https://github.com/rails/strong_parameters

参见:http://guides.rubyonrails.org/association_basics.html

,并采取特别命名说明 - 单数和复数,camelcase和匈牙利符号,大写和小写,它们都有自己的位置和含义,教程通常会很好地带你通过它

Ruby和Rails非常漂亮,强大的,但只有如果y你让他们。如果你仍然在编写Java,那么在语言中固有的好处将不知怎么注入你的代码。

+0

感谢您的详细解答! 。直到这一刻不知道:通过。我是begginer,感谢你的笔记,我的代码 –

+0

@NikitaHarlov,np :)在做基本教程的时候,一条经验法则是“如果它看起来实施起来有点复杂,几乎肯定会有一种内置的方式来实现它“:)并欢迎来到铁轨 – bbozo