开发者

Two has_may association with Same model Rail 3

开发者 https://www.devze.com 2023-02-19 16:34 出处:网络
Hi im quite beginner in rails. i have a problem suggestion will be appreciated. i have two model \"user\" and \"asset\"

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 <开发者_如何学Go 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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号