简体   繁体   English

ActiveModel关联和Rails控制台

[英]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: 现在,我想使用Rails控制台进行数据如下:

> 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? 如何在Rails控制台中做到这一点? 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 user_id添加为rental_units表中的整数列

  2. add has_many :rental_units in your User model User模型中添加has_many :rental_units

Then you can use unit.user = user to build the relationship 然后可以使用unit.user = user建立关系

Update: 更新:

For adding column in database, you need to add a file in /db/migrate like: 要在数据库中添加列,您需要在/ db / migrate中添加一个文件,如下所示:

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

And run rake db:migrate in console 并在控制台中运行rake db:migrate

You will need to 您将需要

  1. Add reference to rental_unit: use rails command to generate the migration 添加对Rental_unit的引用:使用rails命令生成迁移

     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 2.在用户模型中添加关联

    class User < ActiveRecord::Base
        has_many :rental_units
    end

Then test in console, you should be able to associate it. 然后在控制台中测试,您应该可以将其关联。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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