I am looking to setup a relationship where a user can create a post and tag that post. That post and those tags belong to that user.
I've been trying to debug this for the last three days. I don't know why when I save my Post, the user_id does not populate in the Tag model. I added the user_id into the Tag model.
I apologize in advance for the excessive code.
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
ActiveRecord::Schema.define(:version => 20121031012555) do
create_table "posts", :force => true do |t|
t.integer "user_id"
t.string "summary"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "taggings", :force => true do |t|
t.integer "post_id"
t.integer "tag_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "taggings", ["post_id"], :name => "index_taggings_on_post_id"
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
create_table "tags", :force => true do |t|
t.string "name"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "username"
t.string "email"
t.string "crypted_password"
t.string "password_salt"
t.string "persistence_token"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "role"
end
end
In the post Model:
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(tag_name)
tagging = self.taggings.new
tagging.tag_id = tag.id
end
end
has_and_belongs_to_many
relation for that. That helps you to avoid that dummy destroy. – ck3gtaggings
after assigningtagging.tag_id = tag.id
. And I don't see where you trying to saveuser_id
– ck3g