两个 has_may 与同一型号 Rail 3 关联

发布于 2024-10-26 07:39:03 字数 959 浏览 1 评论 0原文

嗨,我是 Rails 的初学者。我有问题建议将不胜感激。 我有两个模型“用户”和“资产” “资产”是由“用户”创建的,并且“资产”可以分配给“用户”模式现在

Asset { id,name,creator_id,assigned_to_id,price,...}

User{ id,name,....}

位于资产模型类关联中,

class Asset < ActiveRecord::Base
{
 #validation
belongs_to :creator ,:class_name=>'User'
belongs_to :assigned_to, :class_name=>'User' ,:foreign_key=>'assigned_to_id'
}

并且用户模型

class User < ActiveRecord::Base
{
#any validation and other stuff
has_many :assets #did not specify either this association  is for creator , or   assigned_to  user.how can is specify that??
}

现在位于资产显示视图中我可以获取创建者名称,

@asset.creator.name

但不能分配给名称

@asset.assigned_to.name =>(error is )undefined method `first_name' for nil:NilClas

和 @asset.assigned_to_id.name=>(错误是)1:Fixnum 的未定义方法“first_name”

任何建议我如何与同一模型进行双重关联

Hi im quite beginner in rails. i have a problem suggestion will be appreciated.
i have two model "user" and "asset"
an "asset" is created by a "user" and asset" can be assigned to a "user" schema is

Asset { id,name,creator_id,assigned_to_id,price,...}

User{ id,name,....}

now in Asset model class association are

class Asset < ActiveRecord::Base
{
 #validation
belongs_to :creator ,:class_name=>'User'
belongs_to :assigned_to, :class_name=>'User' ,:foreign_key=>'assigned_to_id'
}

and User Model is

class User < ActiveRecord::Base
{
#any validation and other stuff
has_many :assets #did not specify either this association  is for creator , or   assigned_to  user.how can is specify that??
}

now in Asset show view i can obtain creator name with

@asset.creator.name

but can't assigned_to name

@asset.assigned_to.name =>(error is )undefined method `first_name' for nil:NilClas

and
@asset.assigned_to_id.name=>(error is) undefined method `first_name' for 1:Fixnum

any suggestion how can i make double association with same model

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

葬花如无物 2024-11-02 07:39:03

好的解决方案在我的最后评论中。
具有相同模型的多个关系

class Asset < ActiveRecord::Base

belongs_to :creator ,:class_name=>'User'
belongs_to :assigned_to, :class_name=>'User' 

end

user.rb

class User < ActiveRecord::Base

has_many :created_assets, :foreign_key => 'creator_id', :class_name => 'Asset'
has_many :assigned_assets , :foreign_key => 'assigned_to_id', :class_name => 'Asset'

end

ok solution was in my last comment.
Multiple relation with same model

class Asset < ActiveRecord::Base

belongs_to :creator ,:class_name=>'User'
belongs_to :assigned_to, :class_name=>'User' 

end

user.rb

class User < ActiveRecord::Base

has_many :created_assets, :foreign_key => 'creator_id', :class_name => 'Asset'
has_many :assigned_assets , :foreign_key => 'assigned_to_id', :class_name => 'Asset'

end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文