2014-01-22 74 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