【发布时间】:2012-10-26 01:17:55
【问题描述】:
我有一个创建帖子的表单。此表单在帖子上也有标签,并且归用户所有。该表单使用虚拟属性:tag_ids。
我想做这样的事情,您可以在其中找到_or_create_by_name_and_user_id,然后传递 current_user.id。
def tag_ids=(tags_string)
self.taggings.destroy_all
tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
tag_names.each do |tag_name|
tag = Tag.find_or_create_by_name_and_user_id(tag_name, current_user.id)
tagging = self.taggings.new
tagging.tag_id = tag.id
end
end
从我读到的内容来看,这不是它应该如何工作的。应该在 PostsContoller 创建方法中调用当前用户。
def create
@post = Post.new(params[:post])
@post.user = current_user
respond_to do |format|
if params[:commit]
@post.save
... 结束
这是我卡住的地方。 如果参数传递了所有属性,我如何将 current_user id 注入具有 :name 和 :user_id 属性的标签模型中?
我还读到,由于我的关联,这应该可以工作。
用户 - has_many 帖子; has_many 标签
发布 - 属于_to用户; has_many 标签; has_many 标签通过标签
标签 - 有很多标签; has_many 通过标签发布帖子;属于用户
标记 - belongs_to 帖子;属于_to标签
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord