Need help in troubleshooting association in Rails !
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
<%= @user.posts %>
in my show.html.erb file. But I get only the following display:-
Name: saran
Email: saran.saran007@gmail.com
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.
Its
class User
has_many :posts
end
Not
has_many :post
Edit and Update your results.
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.
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 %>
精彩评论