Question

In the console

a = Reported.new

This works. After tinkering.

a.profile  = Profile.first

But it's not what I want! I want a.profile to even exist. I want a.reported_by to be a profile! And I want a.reported to be a profile!

Again what I want is

a.reported_by = Profile.last #or any such profile
a.reported = Profile.first #or any such profile

Model

class Profile < ActiveRecord::Base
  has_many :reported, dependent: :destroy

Migration

It doesn't have a reported column, I am not sure about the right way to implement that either.

class CreateReporteds < ActiveRecord::Migration
  def change
    create_table :reporteds do |t|
      t.belongs_to :profile
      t.integer :reported_by
      t.string :reason
      t.timestamps
    end
  end
end
Was it helpful?

Solution

Your migration seems... off. I've never seen t.belongs_to :something in a migration - shouldn't it be t.integer :profile_id? (I couldn't find documentation supporting the belongs_to syntax there).

If you want Reported#reported_by to return a Profile, then you need a reported_by_id integer on it, NOT a reported_by integer. Rails has a convention where you should make your referenced objects (in this case, a belongs_to :reported_by relationship) use the relationship_id format for it's foreign key.

Then you should have this in your class:

class Reported < ActiveRecord::Base
  belongs_to :reported_by, class_name: "Profile"
end

This will make it so it uses reported_by_id as the foreign key for a Profile object, but return it as Reported#reported_by.

Then:

class Profile < ActiveRecord::Base
  has_many :reporteds, foreign_key: 'reported_by_id'
end

Should let you do Profile#reporteds

And your migration would look like this:

class CreateReporteds < ActiveRecord::Migration
  def change
    create_table :reporteds do |t|
      t.integer :reported_by_id
      t.string :reason
      t.timestamps
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top