Skip to content

Instantly share code, notes, and snippets.

@luciuschoi
Created March 21, 2016 10:17
Show Gist options
  • Save luciuschoi/31d355531749b396c72f to your computer and use it in GitHub Desktop.
Save luciuschoi/31d355531749b396c72f to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
has_many :posts
has_many :shares
has_many :shared_posts, class_name: 'Post', through: :shares, source: :post
end
class Share < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :shares
has_many :shared_users, class_name: 'User', through: :shares, source: :user
end
@luciuschoi
Copy link
Author

$ rails g model User name
$ rails g model Post user:references title content:text
$ rails g model Share user:references post:references
$ rake db:migrate

그리고 rake db:console 하신 후 테스트해 볼 수 있습니다.

irb> user1 = User.create! name: 'user1'
irb> user2 = User.create! name: 'user2'
irb> post1 = user1.posts.create! title: 'user1 post'
irb> user2.shared_posts << post1
irb> user2.shared_posts.last

마지막 코드라인에서 방금 전에 공유한 글을 볼 수 있게 됩니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment