2013-08-29 76 views
2

我创建一个示例项目,但是当我试图创建一个新的职位得到一个错误“未定义的方法创建无类”未定义的方法创建无类

我的代码如下。

user.rb

class User < ActiveRecord::Base 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
    has_one :post, dependent: :destroy 
end 

post.rb

class Post < ActiveRecord::Base 
    belongs_to :user 
end 

posts_controller.rb

class PostsController < ApplicationController 
    def create 
    @user = current_user 
    if @user.post.blank? 
     @post = @user.post.create(params[:post].permit(:title, :text)) 
    end 
    redirect_to user_root_path 
    end 
end 

new.html.erb

<%= form_for([current_user, current_user.build_post]) do |f| %> 
    <p> 
    <%= f.label :title %><br> 
    <%= f.text_field :title %> 
    </p> 

    <p> 
    <%= f.label :text %><br> 
    <%= f.text_area :text %> 
    </p> 

    <p> 
    <%= f.submit %> 
    </p> 
<% end %> 

但尝试了很多次后,我做了一些改变,它开始工作,但我不知道两个代码之间有什么区别。

user.rb

class User < ActiveRecord::Base 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
    has_many :posts, dependent: :destroy 
end 

post.rb

class Post < ActiveRecord::Base 
    belongs_to :user 
end 

posts_controller.rb

class PostsController < ApplicationController 
    def create 
    @user = current_user 
    if @user.posts.blank? 
     @post = @user.posts.create(params[:post].permit(:title, :text)) 
    end 
    redirect_to user_root_path 
    end 
end 

new.html.erb

<%= form_for([current_user, current_user.posts.build]) do |f| %> 
    <p> 
    <%= f.label :title %><br> 
    <%= f.text_field :title %> 
    </p> 

    <p> 
    <%= f.label :text %><br> 
    <%= f.text_area :text %> 
    </p> 

    <p> 
    <%= f.submit %> 
    </p> 
<% end %> 

我的routes.rb是

UserBlog::Application.routes.draw do 
    devise_for :users, controllers: { registrations: "registrations" } 

    resources :users do 
    resources :posts 
    end 
    # You can have the root of your site routed with "root" 
    root 'home#index' 
end 

请帮帮我,告诉我是什么这两个代码之间的区别?

回答

24

区别在于添加的助手方法允许您构建或创建新的关联对象。 has_onehas_many关联相比略有不同。

对于has_one association,创建新关联对象的方法为user.create_post

对于has_many association,创建新关联对象的方法是user.posts.create

+0

感谢您使用has_many关联语法。 – jamesdlivesinatree

相关问题