1

I am RoR noob so this might be a simple problem for someone. I have created two models - User and Feedback and I have two tables associated with them. users and feedbacks.

Now I want to create a relationship table with user_id as one column and feeback_id as the other column.

Do I create a model or just a migration? I am confused.

Here are my user and feedback migrations.

class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
    t.string "first_name"
    t.string "last_name"
    t.string "email"
    t.string "phone"
    t.string "password_hashed"
    t.string "password_salt"
    t.boolean "isdeleted", :default => false
    t.timestamps
end
end

def self.down
drop_table :users
end
end

class CreateFeedbacks < ActiveRecord::Migration
def self.up
create_table :feedbacks do |t|
    t.text "feedback"
    t.integer "rating"  
    t.boolean "isdeleted", :default => false
    t.timestamps
end
end
def self.down
drop_table :feedbacks
end
end

Now do I create a model??? >rails generate model FeedbackUserJoinTable ? Or just a migration like this ??

class CreateFeedbackUserJoinTable < ActiveRecord::Migration
def change
create_table :feedbacks_users, :id => false do |t|
  t.integer :feedback_id
  t.integer :user_id
end
end
end
countdrak
  • 83
  • 2
  • 4

2 Answers2

3

I like this answer to another SO question on has_and_belongs_to_many. Basically use HABTM relationships if the relationships between users and feedbacks will remain simple.

If you foresee that these relationships won't remain simple, you should create a join model between the two and use has_many ..., :through => .... That way, when you want to add properties to the relationships between a particular pair of User and Feedback objects, you can define those properties on the join model.

Community
  • 1
  • 1
Eric Hu
  • 18,048
  • 9
  • 51
  • 67
  • I am total noob at RoR. Can i first create a migration to create the join table but if things get more complex can define a model afterwards? – countdrak Jul 23 '11 at 22:41
  • You can definitely do that. You may have some spaghetti code that you'll have to untangle, but that's part of the learning process. Then again, maybe your user/feedback needs won't change and this will remain the ideal solution for you. Your approach makes sense given what you've written. At this point of the design it's just important to **think* about what your needs are, which it sounds like you've done. – Eric Hu Jul 25 '11 at 18:36
2

You do not need to create a model. Just create the migration as you have written :)

Zach Inglis
  • 1,242
  • 1
  • 14
  • 28
  • How does it know to create a relationship between those two tables? Is it because they're both in the same file? – arshbot Nov 05 '17 at 17:13