无法通过rails中的表单在数据库中创建新记录

时间:2013-09-05 09:53:22

标签: ruby-on-rails sqlite

控制器

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

画廊#显示:

<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

绘画形式#news 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 称为方法?

有没有办法解决这个问题?任何帮助表示感谢!

2 个答案:

答案 0 :(得分:1)

问题是我的模型应该如下:

class Painting < ActiveRecord::Base
  attr_accessible :gallery_id, :image, :name, :remote_image_url
  belongs_to :gallery
  mount_uploader :image, ImageUploader
end

因为我使用Carrierwave上传。

答案 1 :(得分:0)

<%= link_to 'Add a painting', new_painting_path(:gallery_id => @gallery) %>

您需要更改新操作。

def new
        @painting = Painting.new(gallery_id: params[:gallery_id])
end