How can I have two separate foreign keys in a single model that associate in the same way with the same other model?
I have two columns in a location model that should both associate with the user model (a 'created_by' column and an 'updated_by' column).
The relevant part of my Locations 'show' view looks like this at the moment:
<p>
Created on <%= @location.created_at %> by <%= @location.created_by %><br />
Last updated on <%= @location.updated_at %> by <%= @location.updated_by %>
</p>
... which obviously just gives me the IDs that I put in 'created_by' and 'updated_by' respectively.
I've tried the following association:
class Location < ActiveRecord::Base
belongs_to :user, :foreign_key => "created_by"
belongs_to :user, :foreign_key => "updated_by"
end
... with this in my view:
<p>
Created on <%= @location.created_at %> by <%= @location.us开发者_运维知识库er.name %><br />
Last updated on <%= @location.updated_at %> by <%= @location.user.name %>
</p>
... but that just throws a "NoMethodError in Locations#show - undefined method `name' for nil:NilClass"
(*oddly, it does display the correct user's name in both places if the 'created_by' and 'updated_by' user happen to be the same*)
How can I have two separate foreign keys in a single model that associate in the same way with the same other model?
try this
class Location < ActiveRecord::Base
belongs_to :user_created,:class_name=>"User", :foreign_key => "created_by"
belongs_to :user_updated,:class_name=>"User", :foreign_key => "updated_by"
end
and apply
@location.user_created.name and @location.user_updated.name
What if you use @location.updated_by.name and @location.created_by.name?
精彩评论