简体   繁体   中英

ActiveModel association and rails console

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?

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM