控制器:
class PaintingsController < ApplicationController
def new
@painting = Painting.new(gallery_id: params[:painting])
end
def create
@painting = Painting.new(params[:painting])
if @painting.save
flash[:notice] = "Painting successfully added to gallery"
redirect_to @painting.gallery
else
render 'new'
end
end
end
画廊#show:
<h1><%= @gallery.name %></h1>
.
.
.
<%= link_to 'Add a painting', new_painting_path(:gallery_id => @gallery) %>
型号:
class Painting < ActiveRecord::Base
attr_accessible :gallery_id, :image, :name, :remote_image_url
belongs_to :gallery
end
绘画中的形式#new view :
<%= form_for @painting do |f| %>
<%= f.hidden_field :gallery_id %>
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<p>
<%= f.file_field :image %>
</p>
<p>
<%= f.label :remote_image_url %>
<%= f.text_field :remote_image_url %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
当我提交此表单时,我收到一条错误消息:
ActiveRecord::StatementInvalid in PaintingsController#create...NoMethodError: undefined method 'name' for nil:NilClass: INSERT INTO "paintings" ("created_at", "gallery_id", "image", "name", "remote_image_url", "updated_at") VALUES (?, ?, ?, ?, ?, ?)
我以前从未见过这样的错误,对此我感到非常困惑。我猜它无法将记录保存到数据库中。但是为什么它调用name作为方法呢?
有没有办法来解决这个问题?任何帮助表示感谢!