1

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

skaffman
  • 398,947
  • 96
  • 818
  • 769
Naveed
  • 11,057
  • 2
  • 44
  • 63
  • after reading [link](http://stackoverflow.com/questions/5149128/rails-3-multiple-has-one-associations-seeding) i have changed my User model class User 'creator_id', :class_name => 'Asset' has_many :assigned_assets , :foreign_key => 'assigned_to_id', :class_name => 'Asset' } and asset model is unchanged now it worked well in console output of console is u=User.new :first_name=>'foo' u.id=12 u.inspect=>"# also u2.inspect=>"# ...more on next comment – Naveed Mar 24 '11 at 12:47
  • now lets create Asset irb(main):032:0> asset=Asset.new :assigned_to_id=>u,:creator_id=>u2,:name=>'Android' => # now asset.assigned_to.name=>(error) undefined method `name' for nil:NilClass and same error for asset.creator.first_name but if i assign after declaring asset like a.assigned_to=u ,a.creator=u2 now a.assigned_to.first_name=>'bar' and a.creator.first_name=>'foo' {interesting} but these all is for console.in views only asset.creator.first_name works plz any suggestion im stuck here – Naveed Mar 24 '11 at 13:00

1 Answers1

1

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
Community
  • 1
  • 1
Naveed
  • 11,057
  • 2
  • 44
  • 63