简体   繁体   中英

Rails model and scaffold for Posts and Likes

I would like to generate a model and scaffold for a "Like" feature in my application. The application has a "Post" model and a "User" model. The users can "Like" the different posts (just like any other social network software)

I am using mongoid and ROR 5.

The User model:

class User
  include Mongoid::Document
  field :created_at, type: String
  field :updated_at, type: String

  has_many :posts
end

The Post model:

class Post
  include Mongoid::Document
  field :created_at, type: String
  field :updated_at, type: String

  belongs_to :user        
end

What would be a proper "Like" model? My best guess was that the "Like" should be embedded in the User model, and "belongs_to" a Post.

How do I scaffold the Like model? How would the "User" or the "Post" model change as a result?

It really depends on how you use the collection.

When you embed the Like collection in User , but want to display like count on every posts, then the embedded solution seems redundant. And vice versa with embed to Post

The easiest way that you can create an independent collection Like without affecting User or Post

class Like
  include Mongoid::Document
  field :user_id, type: String
  field :post_id, type: String
end

And use it as SQL relation ( same with the relation between User and Post )

class User
  # ...
  has_many :likes
end

class Post
  # ...
  has_many :likes
end

You need some extra check when creating Like to make sure a user can like a post only once.

For extra speed ( without care about structure ), you can skip the Like collection and embed references directly to User and Post . Ofcourse this way need more extra check when do the like action

class User
  # ...
  field :liked_post_ids, type: Array, default: []
end

class Post
  # ...
  field :liked_user_ids, type: Array, default: []
end

In NoSQL world, the structure depends on how you use the data, not how beautiful it is. But in my opinion, you should create the independent Like collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM