2014-09-26 74 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 
相关问题