Mike
Mike

Reputation: 137

Ruby on rails associations not working

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

Answers (3)

Paul Richter
Paul Richter

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

usha
usha

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

Thaha kp
Thaha kp

Reputation: 3709

belongs_to :user not belongs_to :User

same issue with Clans

Upvotes: 0

Related Questions