我在rails项目中遇到了一个很棒的错误。我有一个控制器" article.rb"。我使用回形针来附加多个图像,为此我使用了一个模型" article_image"。当我采取行动新建一篇新文章并检查新记录时,每件事情都可以。我收到以下错误:
未定义的方法`new_record?'为零: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
类文章&lt;的ActiveRecord ::基
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? %>
我使用&#39; paperclip&#39;,&#39;〜&gt; 4.2.1&#39;在这个项目中。任何人都可以帮我找到问题吗?
答案 0 :(得分:1)
articles_controller.rb中的更改
def article_params
params.require(:articles).permit(:title,:position,:visible,:body,:created_at, article_images_attributes: [:photo])
end
并在views / article / new / html.erb
中<%= f.fields_for :article_images do |builder| %>
我希望它有效