Ann
Ann

Reputation: 139

how to add a foreign key? Id's are empty in the table

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

Upvotes: 1

Views: 66

Answers (2)

DustinFisher
DustinFisher

Reputation: 396

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

Upvotes: 1

baron816
baron816

Reputation: 701

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.

Upvotes: 1

Related Questions