定义Ruby on Rails关系

时间:2015-02-01 02:52:02

标签: ruby-on-rails ruby model relationship

我有以下型号:

用户:

UserID,FirstName,LastName,State,Gender,Verified,UserTypeID

以下状态:

StatusID,Message,PostDate,UserID

UserTypes

UserTypeID,Description,Enabled

我如何恰当地将这些关系联系起来?我有一个状态下来,但不确定UserTypes

class User < ActiveRecord::Base
    has_many :statuses
    #AssociationToUserTypes
end

class Status < ActiveRecord::Base
    belongs_to :user
end

class UserType < ActiveRecord::Base
    #AssociationTouUsers
end

我生成的迁移中是否有任何内容需要声明?

1 个答案:

答案 0 :(得分:1)

class UserType < ActiveRecord::Base
  has_many :users, foreigner_key: "UserTypeID"
end

Rails会尝试使用user_type_id查找列,因此我们需要指定自定义。

顺便说一句,如果你使用rails生成器,它会更容易:

rails g model user first_name:string last_name:string state:string gender:boolean verified:boolean user_type:references

此命令将生成迁移,模型,空测试文件。您还可以使用CamelCase作为列名。

相关问题