Reputation: 137
I have two files.
clans.rb
class Clans < ActiveRecord::Base
belongs_to :User
end
user.rb
class User < ActiveRecord::Base
has_one :Clan
end
I also have two mysql tables.
clans: id | name | prefix | description | user_id
users: id | username | password | email | bindcode
clans.user_id being users.id of the clan leader.
In my code I can use the following in show.html.erb and it gives me the clan name.
<%= Clans.find(params[:id]).name %>
But I want to be able to do: Clans.find(params[:id]).leader.(users fields) Example:
<%= Clans.find(params[:id]).leader.username %>
How can I achieve this?
Upvotes: 0
Views: 2134
Reputation: 11082
There are two ways you can achieve this:
belongs_to :leader, :class_name=>"User", :foreign_key=>"user_id"
Or
belongs_to :user
delegate :leader, :to=>:user
Note: The latter version will still allow you to do clan.user
, as well as clan.leader
.
Upvotes: 1
Reputation: 29369
class Clan < ActiveRecord::Base
belongs_to :leader, :class_name => "User", :foreign_key => "user_id"
end
class User < ActiveRecord::Base
has_one :clan
end
Notice the class change from Clans
to Clan
and
association change from has_one :Clan
to has_one :clan
Upvotes: 1