Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Undefined method create for nil class

I am creating a sample project but when I am trying to create a new post getting an error "undefined method create for nil class"

My code is as follows.

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 %>

But after trying so many times i have made some changes and it started working but i dont know what is the difference between both the codes.

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 %>

my routes.rb is

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

Please help me and tell me what is the difference between both the codes ?

like image 245
Amit Sharma Avatar asked Aug 29 '13 08:08

Amit Sharma


1 Answers

The difference is in the helper methods that are added allowing you to build or create a new association object. The approach is slightly different for a has_one compared to a has_many association.

For a has_one association the method to create a new associated object would be user.create_post.

For a has_many association the method to create a new associated object would be user.posts.create.

like image 89
Shadwell Avatar answered Nov 02 '22 19:11

Shadwell