I get a wonderful error in a rails project. I have a controller "article.rb". I use paperclip to attach multiple images and for that I use a model "article_image". Every things are ok when I go to action new to create a new article and check for new record. I get the following error:
undefined method `new_record?' for nil:NilClass
articles_controller.rb
class ArticlesController < ApplicationController
before_action :confirm_logged_in
def index
@articles= Article.paginate(page: params[:page],per_page:15).sorted
end
def new
@articles=Article.new()
3.times {@articles.article_images.build}
end
def create
@articles= Article.new(article_params)
if @articles.save
flash[:notice]="article created successfully"
redirect_to(:action =>"index")
else
render("new")
end
end
def show
@articles= Article.find(params[:id])
end
def edit
@articles= Article.find(params[:id])
4.times {@articles.article_images.build}
end
def update
@articles=Article.find(params[:id])
if @articles.update_attributes(article_params)
flash[:notice]="Article updated successfully"
redirect_to(:action=>"show",:id=>@articles.id)
else
render("edit")
end
end
def delete
@articles= Article.find(params[:id])
end
def destroy
@articles=Article.find(params[:id])
@articles.destroy
redirect_to(:action => 'index')
end
private
def article_params
params.require(:articles).permit(:title,:position,:visible,:body,:created_at, article_imgs_attributes: [:photo])
end
end
models/article.rb
class Article < ActiveRecord::Base
has_many :article_images, :dependent => :destroy
accepts_nested_attributes_for :article_images
belongs_to :admin_user
end
models/article_image.rb
class ArticleImage < ActiveRecord::Base
belongs_to :article
has_attached_file :photo, :styles => {:medium => "300x300>", :thumb => "100x100#"}
validates_attachment_presence :photo
validates_attachment_size :photo, :less_than => 5.megabytes
validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/
end
view/article/new/html.erb
<div class="page-header"><h1>Articles</h1></div>
<%= link_to("back to article",{:action =>"index"}, :class =>"action index") %>
<%= form_for(:articles, :html =>{:multipart => true}, :url=>{:action =>'create'}) do |f| %>
<%= f.fields_for :article_imgs do |builder| %>
<% if builder.object.new_record? %>
<p>
<%= builder.label :photo, "Image File" %>
<%= builder.file_field :photo %>
</p>
<% end %>
<% end %>
<% end %>
<div class="form-submit">
<%= submit_tag("create article") %>
</div>
<% end %>
</div>
getting error in
> <% if builder.object.new_record? %>
I use 'paperclip', '~> 4.2.1' in this project. Any one can help me to find the problem?
fields_for
returns nil whenobject
is called. That's where your error comes from - nil doesn't have anew_record?
method. – fzzfzzfzz<% if builder.object.new_record? %>
what you are trying to achieve? – Pavan