0

So I have created two models:

rails g scaffold user name email

and

rails g scaffold rental_unit address rooms:integer bathrooms:integer price_cents:integer

and defined association as follow:

class RentalUnit < ActiveRecord::Base
  belongs_to :user
end

Now, I want to data using rails console as follow:

> user = User.new
> user.name = "John Doe"
> user.email = "test@example.com"
> user.save!    
> unit = RentalUnit.new
> unit.address = "abc street"   
> unit.rooms = 4    
> unit.bathrooms = 2

but I am unable to associate above record using:

unit.user = user

How do I do that in rails console? What is the better way to define this relationship using generators?

Akadisoft
  • 306
  • 1
  • 2
  • 13

2 Answers2

2

You need to build the association as follow:

  1. Add user_id as integer column in your rental_units table

  2. add has_many :rental_units in your User model

Then you can use unit.user = user to build the relationship

Update:

For adding column in database, you need to add a file in /db/migrate like:

class AddUserIdToRentalUnits < ActiveRecord::Migration
  def change
    add_column :rental_units, :user_id, :integer
  end
end

And run rake db:migrate in console

Yang
  • 1,915
  • 1
  • 9
  • 15
  • How to add user_id column in rental_units. should I just edit model file or use scaffold generator? – Akadisoft Nov 27 '15 at 00:24
  • Here is the doc you should read to handle database migration: http://guides.rubyonrails.org/active_record_migrations.html – Yang Nov 27 '15 at 00:29
  • `unit.user = User.first User Load (0.2ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1` got this: `ActiveModel::MissingAttributeError: can't write unknown attribute `user_id`` – Akadisoft Nov 27 '15 at 00:56
  • Do you have attribute `user_id` in your `rental_units` table? – Yang Nov 27 '15 at 01:35
2

You will need to

  1. Add reference to rental_unit: use rails command to generate the migration

    rails g migration AddUserToRentalUnits user:references
    

or manually create a migration

    class AddUserToRentalUnits < ActiveRecord::Migration
        def change
            add_reference :rental_units, :user, index: true
        end
    end

    rake db:migrate

2. Add association in User Model

    class User < ActiveRecord::Base
        has_many :rental_units
    end

Then test in console, you should be able to associate it.

Hope this helps!

Nate Cheng
  • 414
  • 6
  • 11
  • I got the error on executing db:migrate. uninitialized constant ActiveRecord::ConnectionAdapters::SchemaStatements::ReferenceDefinition........abstract/schema_statements.rb:802:in `add_reference' – Akadisoft Nov 27 '15 at 01:12
  • Could be a type from me. class AddUserToRentalUnits < ActiveRecord::Migration, there was an extra e at the end of class name. But it'll be better see your migration file and models file – Nate Cheng Nov 27 '15 at 03:51