Skip to content

Instantly share code, notes, and snippets.

@pwightman
Last active August 29, 2015 13:57
Show Gist options
  • Save pwightman/9611934 to your computer and use it in GitHub Desktop.
Save pwightman/9611934 to your computer and use it in GitHub Desktop.
example.rb
# post.rb
class Post
has_many :tags, :through => :post_tags
has_many :post_tags
end
# tag.rb
class Tag
has_many :posts, :through => :post_tags
has_many :post_tags
end
# post_tag.rb
# This is your join table
class PostTag
belongs_to :tag
belongs_to :post
end
# Then in your code when you need to set something:
tag = Tag.find_by name: "important"
post = Post.find_by title: "Foo bar"
post.tags << tag
# This is your join relationship between the post and the tag
post_tag = post.post_tags.find_by tag_id: tag.id
post_tag.some_custom_field = "the thing you want to save"
post_tag.save
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment