2014-09-26 48 views
0

我有一個Comment對象,該對象在has_and_belongs_to_many關聯中可以有多個與之關聯的Tag對象。在創建時,我希望評論包含與其關聯的標籤,希望不需要另外進行查詢。如何才能做到這一點?創建時返回相關模型

編輯

爲了澄清我的問題,這是我的評論性創建控制器方法:

def create 
    @comment = @current_user.comment!(@post, comment_params[:content]) 

    render :show, status: :created 
end 

這是我comment!方法:

def comment!(yum, content) 
    comment = comments.create!(yum_id: yum.id, content: content) 
    comment.create_activity :create, owner: self, recipient: yum.user 

    mentions = content.scan(/\@\w+/) 
    for mention in mentions 
    if mentioned_user = User.find_by_username(mention.sub("@", "")) 
     mention!(mentioned_user, comment) 
    end 
    end 

    comment 
end 

這是方法該文件檢查文本中保存前執行的標籤:

def create_tags 
    tags = content.scan(/\#[[:alnum:]]+/) 
    for tag in tags 
    tag = tag.sub("#", "") 
    if found_tag = Tag.find_by_content(tag.downcase) 
     self.tags << found_tag 
    else 
     self.tags.build(content: tag) 
    end 
    end 
end 

,這是我的意見JBuilder的觀點:

json.extract! comment, :id, :content, :created_at, :updated_at 

json.tags comment.tags do |tag| 
    json.partial! 'api/v1/shared/tag', tag: tag 
end 

json.user do |json| 
    json.partial! 'api/v1/shared/user', user: comment.user 
end 

我想是要包含在創建註釋時(也是提到想起來了,但解決一個標籤解決其他問題)。當我只顯示那些已經包含的評論時,它的創建只有評論被返回。

+0

您是否想要在創建註釋時創建關聯的標籤,即使用HABTM連接表中正確的'tagID,commentID'行創建實際的數據庫記錄? – nicohvi 2014-10-01 07:07:59

+0

我在推送新評論時會創建關聯標籤。但是我不使用accepters_nested_attributes_for來實現它,因爲標籤在文本本身內。我使用正則表達式將它們拉出並在評論旁邊創建它們,但是當我渲染show view(json)時,只有評論纔會在沒有標籤的情況下呈現。 – 8vius 2014-10-01 15:18:18

回答

0

你需要用where子句來過濾標籤對象:

替換:

tags = content.scan(/\#[[:alnum:]]+/) 
    for tag in tags 
    tag = tag.sub("#", "") 
    if found_tag = Tag.find_by_content(tag.downcase) 
     self.tags << found_tag 
    else 
     self.tags.build(content: tag) 
    end 
    end 

有了:

sent_tags = content.scan(/#([[:alnum:]]+)/).flatten.map &:downcase 
    self.tags = Tag.where(content: tags) # This is the line that saves multiple queries 

    new_tags = sent_tags - tags.map(&:content) 
    new_tags.each do |new_tag| 
    self.tags.build(content: new_tag) 
    end 

注意:

2.1.2 :016 > "some #Thing #qwe".scan(/#([[:alnum:]]+)/).flatten.map &:downcase 
=> ["thing", "qwe"] 

sent_tags將根據需要存儲標籤。

0

如果我正確地理解了這個問題,可以通過覆蓋Comment對象的as_json方法來解決。

# in Comment.rb 

def as_json(options = nil) 
    super((options || {}).merge({ 
    include: :tags  
    }) 
end 

這將確保當評論呈現爲JSON然後散列還包含tags關聯。當您在ActiveRecord對象上調用to_json時會調用as_json方法 - 有關更詳細的解釋,請參閱this優秀的答案,或as_json方法的文檔ActiveModel::Serializershere

如果我誤解了您的問題,請讓我知道! :-)

+0

不,這不是我的問題。我的問題是特定於何時創建評論,而不是在任何情況下呈現。我會發布一些代碼來幫助。 – 8vius 2014-10-01 15:38:48

0

試試這個:

def create 
    @comment = @current_user.comment!(@post, comment_params[:content]) 

    render json: @comment.to_json(include: :tags), status: :created, location: @comment 
end