# Join and Refer In Tables

**URL:** <https://www.ruby-forum.com/t/join-and-refer-in-tables/183684>\
**Category:** Rails\
**Created:** [February 18, 2010, 6:19pm UTC](https://www.ruby-forum.com/t/join-and-refer-in-tables/183684 "2010-02-18T18:19:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kampers](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/54ee81/32.png) [@kampers](https://www.ruby-forum.com/u/kampers)\
**Post date:** [February 18, 2010, 6:19pm UTC](https://www.ruby-forum.com/t/join-and-refer-in-tables/183684/1 "2010-02-18T18:19:28Z")

</div>

OK: I’ve read through this a million times and am still not getting it  
right. I have two tables (posts and authors), with a one(author) to  
many(posts) relationship, and the keys are not named id but user\_name in  
one and screen\_name in the other. I’m trying to join the tables in the  
model, then pull all fields from posts and one additional field from  
author, bio. Here is my stuff:

in models/post.rb

class Post \< ActiveRecord::Base  
has\_one :authors, :primary\_key =\> :user\_name, :foreign\_key =\>  
:screen\_name  
end

in controllers/posts.rb

@postswithauthors = Post.find(:all, :limit =\> 20, :conditions =\>“posted  
between '”+@starthour+"’ and ‘"+@endhour+"’ and  
searchterm=’"+searchterm+"’", :order =\> “posted DESC”, :include =\>  
:authors )

in the view/posts.rb

for x in @postswithauthors  
puts x.user\_name  
puts x.posted  
puts x.post  
puts x.authors.bio  
end

Every time I run this I get something like invalid method “bio”. Been  
over and over all of the association docs and can’t find my error.  
Please help.

Thanks…Chris

---

<div class="post-metadata">

**Author:** ![kampers](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/54ee81/32.png) [@kampers](https://www.ruby-forum.com/u/kampers)\
**Post date:** [February 18, 2010, 6:56pm UTC](https://www.ruby-forum.com/t/join-and-refer-in-tables/183684/2 "2010-02-18T18:56:06Z")

</div>

“has\_one” should only be used in one-to-one relationships.  
This is a one-to-many relationship, so use “belongs\_to :author,  
:foreign\_key =\> :screen\_name” in the model, “:include =\> :author” in the  
controller, and “x.author.bio” in the view.
