Multiple relation with same model

情到浓时终转凉″ 提交于 2019-12-11 08:36:31

问题


i have two model 'Asset' , and 'User' .'Asset' can be assigned to one 'user' and 'asset' is created by one 'user'.here is detail of model classes

class Asset < ActiveRecord::Base
belongs_to :assigned_to ,:class_name=>'User'
belongs_to :creator ,:class_name=>'User'
end

and

class User < ActiveRecord::Base
has_many :assets
end

now in assets show.html.erb i can access name of creator with

 @asset.creator.name

but i can not see name of 'assigned_to'

@asset.assigned_to.name  #gives nothing

both values are successfully saved in database.what is problem?


回答1:


Try printing the values directly to console:

puts @asset.pretty_inspect
puts @asset.assigned_to.pretty_inspect

Something;s not right :)




回答2:


finally my problem is solved here is solution

class Asset < ActiveRecord::Base

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

end

and

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


来源:https://stackoverflow.com/questions/5391964/multiple-relation-with-same-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!