0

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?

1
  • You need to name your user property as 'leader'. Commented Oct 25, 2013 at 13:53

3 Answers 3

1
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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this achieves what I wanted =D
1

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.

Comments

0

belongs_to :user not belongs_to :User

same issue with Clans

1 Comment

This fixed it, mind explaining why? I dont really understand it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.