1

I have three tables. Posts, Replies, Likes. Where users(not implemented yet) can make a Post, Reply and Like the replies as well leave a short comment on why they liked. When a reply is left to the post, it saves post_id (foregin_key) along with reply_id. But when a comment is made for the Like, only the like_id gets passed on and not reply_id and post_id. Nothing to do with controllers but my debugger shows that the reply_id and post_id is blank in the form when posted. Anyway here is my table.

Post.rb

has_may :replies
has_many :likes

Reply.rb

has_many :likes
belongs_to :post

Like.rb

belongs_to :reply
belongs_to :post

migration:

 class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
    t.string :name
    end
  end
 end

class CreateReplies < ActiveRecord::Migration
  def change
    create_table :replies do |t|
    t.string :reply
    t.belongs_to :post, index:true

    end
  end
 end

class CreateLikes < ActiveRecord::Migration
  def change
    create_table :likes do |t|
    t.integer :thumbs
    t.string :comment
    t.belongs_to :post, index:true
    t.belongs_to :reply, index:true

    end
  end
 end

2 Answers 2

1

Likes need to be polymorphic. That way, you won't have a nil field, you're 'likeable' field will just relate to either a reply, or a post. This is actually a classic example of when to use polymorphism.

Sign up to request clarification or add additional context in comments.

Comments

1

Yeah, polymorphic relations is the way to go here.

You would create your Like model like so:

rails g model Like likeable_type:string likeable_id:integer...any other fields

Then in Posts and Replies you would do this:

has_many :likes, as: :likeable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.