Rails belongs_to issue in the views
Im having problems with an association in rails:
Currently I have Post and User models, and the relationship is set this way:
class User < ActiveRecord::Base
attr_accessible :username, :name, :lastname
has_many :posts
end
class Post < ActiveRecord::Base
attr_accessible :title, :body
belongs_to :开发者_运维百科user
end
However, in my app/views/posts/index.html.haml when Im trying to access the username for the post I get this error:
undefined method `name' for nil:NilClass
This is my view:
- title "Posts"
%table
%tr
%th Title
%th Body
%th Author
- for post in @posts
%tr
%td= h post.title
%td= h post.body
%td= h post.user.name
%td= link_to 'Show', post
%td= link_to 'Edit', edit_post_path(post)
%td= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete
%p= link_to "New Post", new_post_path
Any thoughts of what Im doing wrong will be appretiated
First of all check if posts
table has a column named user_id
(you can lookup this table in db/schema.rb)
If not, you probably need to create a migration:
$ ruby script/generate migration AddUserIdToPosts
class AddUserIdToPosts < ActiveRecord::Migration
def self.up
add_column :posts, :user_id, :integer
end
def self.down
remove_column :posts, :user_id
end
end
And then apply changes to the database and schema.rb
$ rake db:migrate
Based on your comments, it looks like you are not associating the actual User
data with the Post
data. You have the associations set up, and after Andrew's answer you seem to now have the database schema set up, but you are not saving the data anywhere.
To do so, update your create method to be something like this:
def PostsController < ActionController::Base
def create
# Assumes @user is already set to whatever user should be associated with the post
post = @user.posts.build(params[:post]) # Where params[:post] are the post inputs from your form
# ...
if post.save
flash[:notice] = "Successfully created post."
redirect_to post
else
render :action => 'new'
end
end
end
@user.posts.build
tells Rails to create a new Post (in memory) and associate it to the @user
User model. An equivalent (but lengthier) way of expressing this is:
post = Post.new(post[:params])
post.user = @user
See the documentation for ActiveRecord::Associations::ClassMethods for more information about what you can do with associations.
精彩评论