New to Rails: Assigning Post to Users

First off, I’m new to rails - this is only my second day playing with
it. Here’s my problem.

I have a post model and a user model. I want to have a has_one
relationship between posts and users. Meaning a post ‘has_one’ user
(author). I feel like I’m doing things right in the model but I’m just
not understanding the “for” loops yet. Take a look at the show.rhtml to
see my messed up for loop.

Any help is appreciated, here is some of the code


V--------show.rhtml--------V

Author

<% for user in @post.users %> <%= user.username %>
<% end %>

V--------post.rb--------V

class Post < ActiveRecord::Base
validates_presence_of :title
has_many :comments
has_one :user
end


V--------user.rb--------V

class User < ActiveRecord::Base
end


V--------rails error page--------V

undefined method `users’ for #Post:0x36edc34

Extracted source (around line #7):

4: <%= link_to ‘Back’, :action => ‘list’ %>

5:
6:

Author


7: <% for user in @post.users %>
8: <%= user.username %>
9:

10: <% end %>

I have a post model and a user model. I want to have a has_one
relationship between posts and users. Meaning a post ‘has_one’ user
(author). I feel like I’m doing things right in the model but I’m just
not understanding the “for” loops yet. Take a look at the show.rhtml to
see my messed up for loop.
Ah - you may be getting slightly mixed up. A post belongs to a user and
a user has many posts. This One to Many relationship should be defined
like this:

class Post < ActiveRecord::Base
belongs_to :user
end

class User < ActiveRecord::Base
has_many :posts
end

has_one is used for a One to One relationship - like that between, for
example, orders and invoices. In this case an order has one invoice and
an invoice has one order.

Hope that helps,

Steve

Curmorpheus <curt.mills@…> writes:

I have a post model and a user model. I want to have a has_one
relationship between posts and users. Meaning a post ‘has_one’ user
(author). I feel like I’m doing things right in the model but I’m just
not understanding the “for” loops yet. Take a look at the show.rhtml to
see my messed up for loop.

It doesn’t sound like you need a loop at all - since a post only has one
user,
you just call post.user

The Rails magic here happens when you put “has_one :user” in the model -
that
line creates the .user and .user= methods among others. If you’d used
“has_many
:users” then a different set of methods would have been created,
including .users

http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html
has more info.

Gareth