开发者

Simple ActiveRecord Association problem

开发者 https://www.devze.com 2023-03-20 05:15 出处:网络
I am learning Rails, so this is a very simple problem. I am trying to associate Users<-Posts in the classic one-to-many style- user\'s own posts.

I am learning Rails, so this is a very simple problem.

I am trying to associate Users<-Posts in the classic one-to-many style- user's own posts.

Here are my models:

class Post < ActiveRecord::Base
  attr_accessible :body
  belongs_to :user  
end

class User < ActiveRecord::Base
  has_many :posts
  attr_accessible :email, :password, :passw开发者_运维问答ord_confirmation
end

I also created the necessary migration:

class AddUserIdToPosts < ActiveRecord::Migration
  def self.up
    add_column :posts, :user_id, :integer
  end

  def self.down
    remove_column :posts, :user_id
  end
end

The problem I'm facing is trying to get rails to see all of this and correctly build the association.

When I call:

@user = User.first
@user.post.build

I get a

NoMethodError: undefined method `post' for #<User:0x10319fbc8>

What have I missed?


it should be user.posts but post.user


If a user has_many Posts the correct call is:

@user.posts.build

Notice the plural posts.


You have declared the association is User model as has_many :posts so the association will be available to you by using @user.posts.build instead of @user.post.build.


You have a has_many relationship so:

@user.posts.build
0

精彩评论

暂无评论...
验证码 换一张
取 消