2013-08-29 74 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

相關問題