0
我在rails項目中遇到了一個奇妙的錯誤。我有一個控制器「article.rb」。我使用回形針來附加多張圖片,並使用「article_image」模型。當我開始採取行動來創建新文章並檢查新記錄時,每件事都可以。我得到以下錯誤:回形針:未定義的方法`new_record?'爲零:NilClass
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
型號/ article.rb
類文章<的ActiveRecord :: Base的
has_many :article_images, :dependent => :destroy
accepts_nested_attributes_for :article_images
belongs_to :admin_user
end
型號/ 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
圖/文/新/ 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>
得到錯誤的
> <% if builder.object.new_record? %>
我用 '回形針', '〜> 4.2.1'。任何人都可以幫助我找到問題?
結果之一,從調用'fields_for'調用'object'時返回nil。這就是你的錯誤來自哪裏 - nil沒有'new_record?'方法。 – fzzfzzfzz
這行的目的是什麼'<%builder.object.new_record? %>'你試圖達到什麼目的? – Pavan