8

我正在创建一个示例项目,但是当我尝试创建一个新帖子时出现错误“为 nil 类创建未定义的方法”

我的代码如下。

用户.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

post_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

新的.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 %>

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

用户.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

post_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

新的.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

请帮助我并告诉我这两个代码有什么区别?

4

1 回答 1

46

不同之处在于添加的辅助方法允许您构建或创建新的关联对象。与关联has_one相比,a的方法略有不同。has_many

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

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

于 2013-08-29T10:42:05.860 回答