我有一個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
我想是要包含在創建註釋時(也是提到想起來了,但解決一個標籤解決其他問題)。當我只顯示那些已經包含的評論時,它的創建只有評論被返回。
您是否想要在創建註釋時創建關聯的標籤,即使用HABTM連接表中正確的'tagID,commentID'行創建實際的數據庫記錄? – nicohvi 2014-10-01 07:07:59
我在推送新評論時會創建關聯標籤。但是我不使用accepters_nested_attributes_for來實現它,因爲標籤在文本本身內。我使用正則表達式將它們拉出並在評論旁邊創建它們,但是當我渲染show view(json)時,只有評論纔會在沒有標籤的情況下呈現。 – 8vius 2014-10-01 15:18:18