Rails nested attributes not saving using carrierwave - ruby-on-rails

I can get the gallery attributes to insert as evident by server log below but picture attributes will not insert as well.
Server response
Started POST "/galleries" for 127.0.0.1 at 2017-05-13 18:19:23 +1000
Processing by GalleriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LACaMz44B9mn/psLYjzs8qrwo9mr0l2OEIPg+VmCn9CdbGhBh9rDUJ6FE0EOwKCj7aZVjbM4+t0YoaFIRX7IEA==", "gallery"=>{"name"=>"Hello", "cover"=>"123456", "picture"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0xb943d50 #tempfile=#<Tempfile:C:/Users/Lee/AppData/Local/Temp/RackMultipart20170513-2604-b2lnrz.jpg>, #original_filename="Skateboard 1.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"gallery[picture][picture]\"; filename=\"Skateboard 1.jpg\"\r\nContent-Type: image/jpeg\r\n">}}, "commit"=>"Create Gallery"}
Unpermitted parameter: picture
(0.0ms) begin transaction
SQL (1.0ms) INSERT INTO "galleries" ("name", "cover", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "Hello"], ["cover", 123456], ["created_at", 2017-05-13 08:19:23 UTC], ["updated_at", 2017-05-13 08:19:23 UTC]]
(65.1ms) commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 74ms (ActiveRecord: 66.1ms)
Started GET "/" for 127.0.0.1 at 2017-05-13 18:19:23 +1000
....
GalleriesController
class GalleriesController < ApplicationController
def new
#gallery = Gallery.new
end
def create
#gallery = Gallery.new(gallery_params)
if #gallery.save
flash[:success] = "Picture created!"
redirect_to root_url
else
render 'new'
end
end
private
def gallery_params
params.require(:gallery).permit(:id, :name, :cover, pictures_attributes: [:id, :gallery_id, :picture, :_destroy])
end
end
_form.html.erb partial rendered from within new.html.erb
<%= form_for #gallery do |f| %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :cover %>
<%= f.text_field :cover %>
</div>
<div id="pictures">
<%= f.fields_for #gallery.pictures do |pic| %>
<%= pic.file_field :picture %>
</div>
<% end %>
<div id="submit">
<%= f.submit %>
</div>
<% end %>
Models, Gallery
class Gallery < ApplicationRecord
has_many :pictures
validates :name, presence: true
validates :cover, presence: true
accepts_nested_attributes_for :pictures, allow_destroy: true
end
Picture
class Picture < ApplicationRecord
belongs_to :gallery
validates :gallery_id, presence: true
validates :picture, presence: true
mount_uploader :picture, PictureUploader
serialize :picture, JSON
end
Migrations, Gallery
class CreateGalleries < ActiveRecord::Migration[5.0]
def change
create_table :galleries do |t|
t.string :name
t.integer :cover
t.timestamps
end
end
end
Picture
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.integer :gallery_id
t.string :picture
t.timestamps
end
end
end

Unpermitted parameter: picture
The error is because your fields_for is wrong. The first parameter of fields_for should be a record_name(which should be :pictures in your case).
fields_for(record_name, record_object = nil, options = {}, &block)
You are passing record_object as a first parameter, which resulting in wrong params and leading to unpermitted error. Changing your code to below should resolve the issue.
<%= f.fields_for :pictures, #gallery.pictures do |pic| %>
<%= pic.file_field :picture %>
<% end %>

Judging by your parameters line here:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LACaMz44B9mn/psLYjzs8qrwo9mr0l2OEIPg+VmCn9CdbGhBh9rDUJ6FE0EOwKCj7aZVjbM4+t0YoaFIRX7IEA==",
"gallery"=>{"name"=>"Hello", "cover"=>"123456",
"picture"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0xb943d50
#tempfile=#<Tempfile:C:/Users/Lee/AppData/Local/Temp/RackMultipart20170513-2604-b2lnrz.jpg>,
#original_filename="Skateboard 1.jpg", #content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"gallery[picture][picture]\";
filename=\"Skateboard 1.jpg\"\r\nContent-Type: image/jpeg\r\n">}}, "commit"=>"Create Gallery"}
and the fact you're getting the result: Unpermitted parameter: picture, you should change your strong parameters to
def gallery_params
params.require(:gallery).permit(:id, :name, :cover, picture: [:id, :gallery_id, :picture, :_destroy])
end

Related

How to get this nested form to create a new object

My Rails 5 application includes two models, Activity and Timeslot.
activity.rb
class Activity < ApplicationRecord
belongs_to :club
has_many :timeslots, :dependent => :destroy
accepts_nested_attributes_for :timeslots
validates :club_id, presence: true
validates :name, presence: true, length: { maximum: 50 }
end
timeslot.rb
class Timeslot < ApplicationRecord
belongs_to :activity
validates :time_start, presence: true
validates :time_end, presence: true
validates :day, presence: true
#validates :activity_id, presence: true (I realised this was causing one of the errors I had)
default_scope -> { order(day: :asc) }
end
When I create my activity, I'd also like to create it's first timeslot on the same page, same form.
new.html.erb
<%= form_for(#activity) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.label :name, "Class name" %>*
<%= f.text_field :name, class: 'form-control' %>
<%= f.fields_for :timeslots do |timeslots_form| %>
<%= timeslots_form.label :time_start, "Start time" %>
<%= timeslots_form.time_select :time_start %>
<%= timeslots_form.label :time_end, "End time" %>
<%= timeslots_form.time_select :time_end %>
<%= timeslots_form.label :day %>
<%= timeslots_form.select :day, (0..6).map {|d| [Date::DAYNAMES[d], d]} %>
<% end %>
</div>
<%= f.submit "Create class", class: "btn btn-primary" %>
<% end %>
My edit/update version of this seems to be working fine.
activities_controller.rb
class ActivitiesController < ApplicationController
...
def new
#activity = Activity.new
#activity.timeslots.build
end
def create
#activity = current_club.activities.build(activity_params)
##activity.timeslots.first.activity_id = #activity.id (I thought this might solve the problem, but didn't)
if #activity.save
flash[:success] = "New class created!"
redirect_to activities_path
else
render 'new'
end
end
def edit
#activity = current_club.activities.find_by(id: params[:id])
#activity.timeslots.build
end
def update
#activity = current_club.activities.find_by(id: params[:id])
if #activity.update_attributes(activity_params)
flash[:sucess] = "Class updated!"
redirect_to edit_activity_path(#activity)
else
render 'edit'
end
end
...
private
def activity_params
params.require(:activity).permit(:name, :active, #active is set to default: true
:timeslots_attributes => [:id,
:time_start,
:time_end,
:day,
:active])
end
end
But whenever I try to create a new activity I get the error message "Timeslots activities must exist".
I feel it's trying to assign the activity_id for timeslot before the activity is created, but I'm not sure. I've tried many things (some of which I've included in my example in comment form) but am unable to work out why I'm getting this error.
Update: Add error log
Started POST "/activities" for 127.0.0.1 at 2016-09-25 18:04:51 +0700
Processing by ActivitiesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xp+dBcWC4cjI6FLpIqhU0RzM4ldZ4JpkFLSyAXcmifL73QqWz6R65EHm/Tj7QxlXnWiBA0axjVXvMZHQ+XKA9A==", "activity"=>{"name"=>"Newest class", "timeslots_attributes"=>{"0"=>{"time_start(1i)"=>"2016", "time_start(2i)"=>"9", "time_start(3i)"=>"25", "time_start(4i)"=>"12", "time_start(5i)"=>"00", "time_end(1i)"=>"2016", "time_end(2i)"=>"9", "time_end(3i)"=>"25", "time_end(4i)"=>"13", "time_end(5i)"=>"30", "day"=>"4"}}}, "commit"=>"Create class"}
Club Load (0.2ms) SELECT "clubs".* FROM "clubs" WHERE "clubs"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
(0.1ms) begin transaction
(0.1ms) rollback transaction
Rendering activities/new.html.erb within layouts/application
Rendered shared/_error_messages.html.erb (1.5ms)
Rendered activities/new.html.erb within layouts/application (16.9ms)
Rendered layouts/_rails_default.html.erb (58.5ms)
Rendered layouts/_shim.html.erb (0.5ms)
Rendered layouts/_header.html.erb (1.7ms)
Rendered layouts/_footer.html.erb (0.8ms)
Completed 200 OK in 111ms (Views: 93.9ms | ActiveRecord: 0.3ms)
You're getting this error because Rails 5 makes belongs_to attribute required by default. Also, the saving mechanism kind of follows:
validate your parent model
validate your child model # validation fails here because parent doesn't have an id yet, because it hasn't been saved
save parent model
save child model
A way to resolve this is to:
class Activity < AR
has_many :timeslots, dependent: :destroy, inverse_of: :activity
accepts_nested_attributes_for :timeslots
end
class Timeslot < AR
belongs_to :activity, inverse_of: :timeslot
end
You could learn more of this here and here

processing by create instead of update

when I attempt to run my code, I got the error above.
I try to add specific attributes to my products, but every time I try to add them to my product, a new one is created instead of just edit the old.
Here is the result :
Started POST "/my_products" for 127.0.0.1 at 2016-01-03 16:33:46 +0100
[localhost] [127.0.0.1] [a6533ae8-475f-4e] Processing by MyProductsController#create as JS
[localhost] [127.0.0.1] [a6533ae8-475f-4e] Parameters: {"utf8"=>"✓", "my_product"=>{"size_name"=>"Gros oeuf", "size_img"=>"big-egg.png", "size_price"=>"40"}, "commit"=>"Choisir"}
[localhost] [127.0.0.1] [a6533ae8-475f-4e] (0.2ms) BEGIN
[localhost] [127.0.0.1] [a6533ae8-475f-4e] SQL (0.3ms) INSERT INTO `my_products` (`size_name`, `size_price`, `size_img`, `created_at`, `updated_at`) VALUES ('Gros oeuf', '40', 'big-egg.png', '2016-01-03 15:33:46', '2016-01-03 15:33:46')
[localhost] [127.0.0.1] [a6533ae8-475f-4e] (2.0ms) COMMIT
My application_controller.rb :
def current_product
if !session[:my_product_id].nil?
MyProduct.find(session[:my_product_id])
else
MyProduct.new
end
end
My Products_controller :
def base
#myproduct = current_product
#size = Size.all
#chocolate = MyProductItem.where(item_category_id: 1)
end
def create
#myproduct = current_product
if #myproduct.update(my_product_params)
redirect_to(:back)
else
render 'new'
end
end
My base.html.erb :
<% #size.each do |size| %>
<div class="Box" >
<p><%= size.name %></p>
<p><%= image_tag size.image, style: 'width:7em;height:auto;' %></p>
<p><%= number_to_currency size.price %></p>
<p><%= size.description.try(:html_safe) %></p>
<%= form_for #myproduct, remote: true do |f| %>
<%= f.hidden_field :size_name, value: size.name %>
<%= f.hidden_field :size_img, value: size.image %>
<%= f.hidden_field :size_price, value: size.price %>
<%= f.submit "Choisir", class: "addtocart", :id => "#orders" %>
<% end %>
</div>
<% end %>
My models :
class MyProduct < ActiveRecord::Base
attr_accessible :name, :slug, :price, :image, :my_product_item_id, :user_id, :size_name, :size_img, :size_price
has_many :elements, dependent: :destroy
has_one :size, dependent: :destroy
belongs_to :user
belongs_to :order
class Size < ActiveRecord::Base
attr_accessible :name, :price, :weight, :image, :description, :object_size
belongs_to :my_product
end
Any idea ?
Add field with proper :my_product_id value into the form:
<%= hidden_field_tag(:my_product_id, #my_product.id) if #my_product %>
If you invoke base action with GET request without parameters new object will be created, for update you must pass to this action parameter my_product_id=value (value is an id of updated product).

Rails Simple Form Association submission not updating

I have a problem with has_many relationships setting up forms that do not update the values after submission.
Example
Upon submission of a new character, vn_id does not get updated and in Rails Consoles when I try to check for characters in a Vn, it returns empty.
I am trying to set up a form for characters which belongs to Vn which will be linked through the association but upon submission, it is not linked to Vn.
class Character < ActiveRecord::Base
validates :name, :presence => true
validates :summary, :presence => true
belongs_to :vn
end
class Vn < ActiveRecord::Base
has_many :characters
validates :name, presence: true
accepts_nested_attributes_for :characters
end
Form to create a new Character
<%= simple_form_for #character do |f| %>
<div class="col-lg-12">
<%= f.input :summary,input_html: {style: "height:150px;"} %>
</div>
<div class="col-lg-12">
<%= f.association :vn, as: :check_boxes %>
</div>
<%= f.button :submit , class: "btn btn-primary" %>
<% end %>
Controllers
class CharactersController < ApplicationController
def show
#character = Character.find(params[:id])
end
def new
#character = Character.new
end
def create
#character = Character.new(char_params)
if #character.save
else
render :action=>"new"
end
end
private
def char_params
params.require(:character).permit(:name, :summary,:voiceactor,:vn_name,vn_id: [])
end
end
class VnsController < ApplicationController
def show
#vn = Vn.find(params[:id])
end
def new
#vn = Vn.new
end
def create
#vn = Vn.new(vn_params)
if #vn.save
else
render :action=>"new"
end
end
private
def vn_params
def vn_params
params.require(:vn).permit(:name, :summary,:genre,:developer,:rating,vn_id: [])
end
end
end
Submission unpermitted vn_id
Parameters: {"utf8"=>"✓", "authenticity_token"=>"O2s6GVs77GGUMC5u3eZ9ebv/0l5u0MwP44yS8WGCQnjgwSgHfkbCmhEOUo6WKIMSMo5IfDuNYtMzyphnT/5cwQ==", "character"=>{"name"=>"2222", "voiceactor"=>"111", "summary"=>"one two tthee", "vn_id"=>"32"}, "commit"=>"Create Character"}
Unpermitted parameter: vn_id
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "characters" ("name", "summary", "voiceactor", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["name", "2222"], ["summary", "one two tthee"], ["voiceactor", "111"], ["created_at", "2015-10-23 10:34:00.285447"], ["updated_at", "2015-10-23 10:34:00.285447"]
The problem is you're trying to permit an array for a singular association.
The f.association input is for your belongs_to association, so why would it allow multiple records?
You can even see how this works here:
The above are methods only for has_many
In short, they don't exist for belongs_to
Thus, when you call f.association :vn, you're populating an attribute vn_id which can then be associated in your database.
The only time you'd have vn_ids is if you used has_many etc.
This means...
def character_params
params.require(:character).permit(:vn_id)
end
with
f.association :vn
... should work
Somehow, changing vn_id: [] in CharactersController back to :vn_id worked.

Rails 4, double-nested models and strong parameters

I am fairly new to Ruby on Rails and began with rails 4 right away.
I have sucessfully nested a Recipe and a Ingredient model so that they can be added in the same form. Next I want to nest quantity within ingredient so that that aswell can be added within the same form. Everything seems to be working fine up until when the quantity of the ingredient is about to be inserted in the database and from this i believe there is something wrong with the strong params in the recipes_controller. But i will post the full code below.
I am using simple_form for the forms.
Thankful for any help!
Here are my models:
class Recipe < ActiveRecord::Base
has_many :comments, dependent: :destroy
has_many :ingredients, dependent: :destroy
accepts_nested_attributes_for :ingredients, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
validates :title, presence: true
validates :desc, presence: true
end
class Ingredient < ActiveRecord::Base
belongs_to :recipe
has_many :quantities, dependent: :destroy
accepts_nested_attributes_for :quantities, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
end
class Quantity < ActiveRecord::Base
belongs_to :ingredient
end
Here is the recipes_controller
class RecipesController < ApplicationController
def new
#recipe = Recipe.new
3.times do
ingredient = #recipe.ingredients.build
1.times {ingredient.quantities.build }
end
end
def create
#recipe = Recipe.new(params[:recipe].permit(:title, :desc, ingredients_attributes: [:id, :recipe_id, :name, :_destroy, quantities_attributes: [:id, :ingredient_id, :amount, :unit, :_destroy]]))
if #recipe.save
redirect_to #recipe
else
render "new"
end
end
def show
#recipe = Recipe.find(params[:id])
end
def edit
#recipe = Recipe.find(params[:id])
end
def update
#recipe = Recipe.find(params[:id])
if #recipe.update(params[:recipe].permit(:title, :desc))
redirect_to #recipe
else
render 'edit'
end
end
def destroy
#recipe = Recipe.find(params[:id])
#recipe.destroy
redirect_to recipes_path
end
def index
#recipes = Recipe.all
end
private
def post_params
params.require(:recipe).permit(:title, :desc, ingredients_attributes: [:id, :recipe_id, :name, :_destroy, quantities_attributes: [:id, :ingredient_id, :amount, :unit, :_destroy]])
end
end
Then i use simple form to create a form for recipe, ingredient and quantity through partials.
_form:
<%= simple_form_for #recipe do |f| %>
<%= f.error_notification %>
<%= f.input :title %>
<%= f.input :desc %>
<%= f.simple_fields_for :ingredients do |builder| %>
<%= render "ingredient_fields", :f => builder %>
<% end %>
<p class="links">
<%= link_to_add_association 'add ingredient', f, :ingredients %>
<p class="links">
<%= f.error :base%>
<%= f.submit %>
<% end %>
Which renders from _ingredients_fields:
<div class="nested-fields">
<%= f.input :name, label: "Ingredient" %>
<%= f.simple_fields_for :quantities do |builder| %>
<%= render "quantities_fields", :f => builder %>
<% end %>
<%= link_to_remove_association "remove", f %>
</div>
which renders from _quantities_fields: [EDITED]
<div class="nested-fields">
<%= f.input :amount %>
<%= f.input :unit %>
</div>
Trying to add new recipes result in the following log statement:
Started POST "/recipes" for 127.0.0.1 at 2013-10-29 14:15:40 +0100
Processing by RecipesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"t6LKgDLwAxaU9xo2ipyCM+j1yfVF9WrI8AoGTX+gRkw=", "recipe"=>{"title"=>"Pancakes", "desc"=>"Tasty", "ingredients_attributes"=>{"0"=>{"name"=>"Milk", "quantities_attributes"=>{"0"=>{"amount"=>"1", "unit"=>"Cup"}}, "_destroy"=>"false"}}}, "commit"=>"Create Recipe"}
[1m[35m (0.1ms)[0m begin transaction
[1m[36mSQL (3.5ms)[0m [1mINSERT INTO "recipes" ("created_at", "desc", "title", "updated_at") VALUES (?, ?, ?, ?)[0m [["created_at", Tue, 29 Oct 2013 13:15:40 UTC +00:00], ["desc", "Tasty"], ["title", "Pancakes"], ["updated_at", Tue, 29 Oct 2013 13:15:40 UTC +00:00]]
[1m[35mSQL (0.4ms)[0m INSERT INTO "ingredients" ("created_at", "name", "recipe_id", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Tue, 29 Oct 2013 13:15:40 UTC +00:00], ["name", "Milk"], ["recipe_id", 27], ["updated_at", Tue, 29 Oct 2013 13:15:40 UTC +00:00]]
[1m[36m (7.8ms)[0m [1mcommit transaction[0m
Redirected to http://www.projectcookbook.dev/recipes/27
Completed 302 Found in 22ms (ActiveRecord: 11.7ms)
You're using similar render for _quantities and _ingredients partials, which is wrong. In _quantities_field you don't need
<%= f.simple_fields_for :quantities do |builder| %>
<%= render "quantities_fields", :f => builder %>
<% end %>
AND should adjust
<%= f.input :name, label: "Quantity" %>
in _quantities_fields.
UPD
I think the problem is in :reject_if-clause at Ingredient model. It should be
:reject_if => lambda { |a| a[:amount].blank? }
bc here you specify conditions for Quantity, not for Ingredient
On code styling:
1) In controller it's better to use relevant name of private method for strong parameters: recipe_params instead of post_params and then use it for creation of new Recipe #recipe = Recipe.new(recipe_params)
2) Current associations between Recipe, Ingredient and Quantity will lead to Ingredient duplication in case two Recipes use similar one. The reason is belongs_to, which define single association. Try another approach (bellow).
BTW. recently I've answered on the similar question. Check it out: How do I reference an existing instance of a model in a nested Rails form?
I thing you are missing in this part
<%= simple_form_for #recipe do |f| %>
it should be
<%= simple_nested_form_for #recipe do |f| %>

Rails + CarrierWave: NoMethodError: undefined method `name' for nil:NilClass

I am using CarrierWave with Rails 3.1. I am getting the following error message when I submit the form (trying to upload an image):
Error Message:
ActiveRecord::StatementInvalid in Admin::PostsController#create
NoMethodError: undefined method `name' for nil:NilClass: INSERT INTO "posts" ("body", "created_at", "draft", "image", "post_type", "title", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?)
Rails.root: /Users/aziz/Sandbox/ruby/rails/Tumblelog
Application Trace | Framework Trace | Full Trace
app/controllers/admin/posts_controller.rb:18:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"za+zNRDGNCcujnCmO726cWCo2ze1rgaXv5bL17JGaek=",
"post"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x000001014aeff0 #original_filename="AzizLight.jpeg",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"post[image]\"; filename=\"AzizLight.jpeg\"\r\nContent-Type: image/jpeg\r\n",
#tempfile=#<File:/var/folders/ky/2ddtbt0d7k1g__2ctr8njcfc0000gn/T/RackMultipart20110918-21704-hp2ajt>>,
"draft"=>"0",
"user_id"=>"2",
"post_type"=>"image"},
"commit"=>"Post"}
The problem is that I don't know where this name comes from and I don't know what variable is being nil, so I can't debug properly (I tried to debug a log before asking here).
Line 18 corresponds to the #post.save line in the following controller:
PostsController:
# ...
def new
#post = Post.new
#form_html_options = (params[:post_type] == "image") ? { :multipart => true } : {}
#form_partial = get_form_partial(params[:post_type])
redirect_to admin_posts_path, :alert => "You tried to create an unknown type of post..." if #form_partial.nil?
#title = "Creating a new post..."
end
def create
#post = Post.new(params[:post])
if #post.save
flash[:success] = "Post created successfully!"
redirect_to admin_post_path(#post)
else
#title = "Creating a new post..."
#form_partial = get_form_partial(params[:post][:post_type])
render 'new'
end
end
# ...
Here other files that might be needed to spot the problem:
Post (model):
attr_accessible :title, :body, :user_id, :draft, :post_type, :image
belongs_to :user
mount_uploader :image_url, ImageUploader
ImageUploader:
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
storage :fog
def extension_white_list
%w(jpg jpeg gif png)
end
end
new.html.erb:
<h1><%= #title %></h1>
<%= form_for #post, :url => admin_posts_path, :html => #form_html_options do |f| %>
<%= render 'form', :f => f %>
<% end %>
_form.html.erb:
<%= render 'error_messages' %>
<%= render #form_partial, :f => f %>
<p class="drop-down">
<%= f.label :draft, 'Status' %>
<%= f.select(:draft, options_for_select([["Published", 0], ["Draft", 1]], (#post.new_record? ? 0: #post.draft))) %>
</p>
<%= f.hidden_field :user_id, :value => #post.user_id || current_user.id %>
<%= f.hidden_field :post_type, :value => #post.post_type || params[:post_type] %>
<p class="button"><%= f.submit "Post", :disable_with => 'Posting...' %></p>
_image_form.html.erb (#form_partial):
<p><%= f.file_field :image %></p>
So what it really going on please?
Your image uploader class was not loaded into your current rails server thread. Reload rails server and it should work fine =).
Make sure you use - mount_uploader :image, ImageUploader in your model like here -
class CarImage < ActiveRecord::Base
belongs_to :car
mount_uploader :image, ImageUploader
end
Regards
Robbie
I experienced the some problem and the cause is (probably always) that the UploadedFile object has been sent to the attribute carrierwave was mounted on. The db adapter cannot serialize this object and will therefore throw this error.
Make sure that:
the uploader has been properly mounted
you don't use write_attribute to write the uploaded file (which was the cause of my problem). Use the accessor instead: model.send('image=', params[:model][:image]). Uglier, but better.
Make sure in your model:
mount_uploader :image, ImageLoader
Remember that :image must be the string/text type.
I came across this post because I had the same error you described, but restarting the server didn't resolve it (as suggested by other answers). In my case, the problem was caused because I used mount_uploader before attr_accessible. By switching them I solved the problem.
I had a similar problem.
Solution was changing:
attr_accessible :title, :body, :user_id, :draft, :post_type, :image
belongs_to :user
mount_uploader :image_url, ImageUploader
to:
attr_accessible :title, :body, :user_id, :draft, :post_type, :image_url
belongs_to :user
mount_uploader :image_url, ImageUploader

Resources