简体   繁体   中英

Can't create new record in database through form in rails

Controller :

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

galleries#show:

<h1><%= @gallery.name %></h1>

.
.
.

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

Model :

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

Form in paintings#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 %>

When I submit this form I get an error that says:
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 (?, ?, ?, ?, ?, ?)

I've never seen an error like this before so really confused about it. I guess it can't save the record to the database. But why is it calling name as a method?

Is there a way to fix this? any help appreciated thanks!

The issue was my model it should read as follows:

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

Because I was using Carrierwave to upload.

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

You need to change the new action.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM