views:

21

answers:

3

I'm new to rails and and I'm on the urge of learning Associations.
I'm using Rails version 3.
I have a user model and post model.My need is as below:-

Models

class User < ActiveRecord::Base  
  has_many :post  
end  

class Post < ActiveRecord::Base  
  belongs_to :user  
  validates_associated :user  
end  

Schema

ActiveRecord::Schema.define(:version => 20101016171256) do  
  create_table "posts", :force => true do |t|  
    t.integer  "sell_or_buy"  
    t.string   "title"  
    t.text     "body"  
    t.integer  "user_id"  <<<<<<< I thought this will help to associate to user model.  
    t.datetime "created_at"  
    t.datetime "updated_at"  
  end  

  create_table "users", :force => true do |t|  
    t.string   "name"  
    t.string   "email"  
    t.string   "password"  
    t.integer  "rank"  
    t.datetime "created_at"  
    t.datetime "updated_at"  
  end  
end

I thought keeping a user_id field and the belongs_to association will do my job, but
when i tried to display all the posts belonging to a user as follows:

<%= @user.posts %>  

in my show.html.erb file. But I get only the following display:-

Name:  saran  

Email: [email protected]  

Password: abcd  

Rank:    
Edit | Back  
Posts  
#<Post:0xb69f47f8>#<Post:0xb69f3024>   

I want to display the associated posts "title" and "body" in a readable format.

Also I'm able to create a post with a user_id in which no user exists!. The validates_associated :user is also not working, Please help me out.

+1  A: 

You are getting the posts as expected in your view... So I'm not sure I understand that part of your question. As to the other part, validates_associated just ensures that the attached object is valid itself, and not if it exists at all. For that you want validates_presence_of. See the docs.

thenduks
I want to display the complete Post in a readable format.I want to display its title and body.
Saran
Well, your question is about the association being broken... Obviously to output the post in readable format you just use the properties in your model and generate markup: `<% @user.posts.each do |post| -%><h2><%= post.title %></h2><p><%= post.body %></p><% end -%>` and so on just like you did with the user to get their name on the page.
thenduks
+3  A: 

Its

class User
  has_many :posts
end

Not

has_many :post

Edit and Update your results.

Shreyas Satish
Very true... but, odd how his code with `has_many :post` correctly finds and outputs Post objects though, eh?
thenduks
A: 

I wrote the following partial for my purpose and it works well :).
Thanks for all your inputs.

<% for post in @user.posts do %>    
   <h3> <%= post.title %> </h3>   
   <%= post.body %>   
<% end %>   
Saran