I have a form to create posts. This form also has tags on the post and it is owned by a user. The form is using a virtual attribute :tag_ids.
I would like to do something like this, where you find_or_create_by_name_and_user_id and then just pass the 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
From what I read this isn't how it should work. The current user should be called in the PostsContoller create method.
def create
@post = Post.new(params[:post])
@post.user = current_user
respond_to do |format|
if params[:commit]
@post.save
... end
This is where I'm stuck. If the params are passing all of the attributes, how can I inject the current_user id into tag model which has a :name and :user_id attribute?
I also read that this should work because of my associations.
User - has_many posts; has_many tags
Post - belongs_to user; has_many taggings; has_many tags through taggings
Tag - has many taggings; has_many posts through taggings; belongs_to user
Tagging - belongs_to post; belongs_to tag