I'm trying to build a very basic Rails app for posting images with a comment. The comment is a required field and the image upload should only go ahead if the comments section has a value, displaying an error message otherwise.
The problem I am having is that even when the comments section is filled in it still displays an error saying that it cannot be blank.
I have tried adding attr_accessor's with the html field names and database values but it makes no difference.
Posts model
class Post < ActiveRecord::Base
has_attached_file :picture, styles: { medium: "300x300>", thumb: "100x100>" }
attr_accessor :picture_file_name
attr_accessor :post_description
validates :description, presence: true
end
Posts controller
class PostsController < ApplicationController
def index
@posts = Post.all
end
def new
@post = Post.new
end
def create
@post = Post.new params[:post].permit(:description, :picture)
if @post.save
redirect_to '/posts'
else
render 'new'
end
end
end
new.html.erb
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form_for @post, :html => { :multipart => true } do |f| %>
<%= f.label :description %>
<%= f.text_area :description %>
<%= f.label :picture %>
<%= f.file_field :picture %>
<%= f.submit %>
<% end %>
Server readout
=> Booting WEBrick
=> Rails 4.0.4 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
[2014-04-20 17:59:07] INFO WEBrick 1.3.1
[2014-04-20 17:59:07] INFO ruby 2.1.0 (2013-12-25) [x86_64-darwin12.0]
[2014-04-20 17:59:07] INFO WEBrick::HTTPServer#start: pid=98772 port=3000
Started POST "/posts" for 127.0.0.1 at 2014-04-20 17:59:21 +0100
ActiveRecord::SchemaMigration Load (0.2ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by PostsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"nVrCEAdT+epbltQWR74jtv1weGaq6H7YbWQKFfJNDTw=", "post"=>{"description"=>"test comment", "picture"=>#<ActionDispatch::Http::UploadedFile:0x0000010242f740 @tempfile=#<Tempfile:/var/folders/lm/vrw53rx91831vrh4228m0mfw0000gn/T/RackMultipart20140420-98772-1c9msrz>, @original_filename="dory_2.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"post[picture]\"; filename=\"dory_2.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Create Post"}
WARNING: Can't mass-assign protected attributes for Post: description, picture
app/controllers/posts_controller.rb:12:in `create'
(0.1ms) begin transaction
(0.1ms) rollback transaction
Rendered posts/new.html.erb within layouts/application (13.1ms)
Completed 200 OK in 105ms (Views: 65.6ms | ActiveRecord: 0.4ms)