在 Rails 关系上定义 Ruby
Defining Ruby on Rails Relationship
我有以下型号:
用户:
用户 ID、名字、姓氏、州、性别、已验证、用户类型 ID
状态:
状态 ID、消息、发布日期、用户 ID
用户类型
用户类型 ID、说明、已启用
我将如何恰当地关联这些关系?我的 Status 已关闭,但不确定 UserTypes
class User < ActiveRecord::Base
has_many :statuses
#AssociationToUserTypes
end
class Status < ActiveRecord::Base
belongs_to :user
end
class UserType < ActiveRecord::Base
#AssociationTouUsers
end
我生成的迁移中是否有任何我需要声明的内容?
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 作为列名。
我有以下型号:
用户:
用户 ID、名字、姓氏、州、性别、已验证、用户类型 ID
状态:
状态 ID、消息、发布日期、用户 ID
用户类型
用户类型 ID、说明、已启用
我将如何恰当地关联这些关系?我的 Status 已关闭,但不确定 UserTypes
class User < ActiveRecord::Base
has_many :statuses
#AssociationToUserTypes
end
class Status < ActiveRecord::Base
belongs_to :user
end
class UserType < ActiveRecord::Base
#AssociationTouUsers
end
我生成的迁移中是否有任何我需要声明的内容?
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 作为列名。