Reputation: 924
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!
Upvotes: 0
Views: 156
Reputation: 924
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.
Upvotes: 1
Reputation: 5734
<%= 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
Upvotes: 0