Error: Validation failed: Images imageable must exist , rails-5.0 , paperclip-5 - paperclip

While i was trying to submit the form, following error occured: Validation failed: Images imageable must exist and render the same new.html.erb view.
If i comment the file field in new.html.erb. Product is being created successfully.
ProductsController:
def new
#product = Product.new
end
def create
#product = Product.create!(product_params)
if #product.save
redirect_to products_path, notice: "Product Created Successfully"
else
render "new"
end
end
def product_params
params.require(:product).permit(:name, :quantity, :price, images_attributes: [:id, :photo, :_destroy])
end
new.html.erb:
<%= nested_form_for #product, html: { multipart: true } do |f|%>
<h2>New</h2>
<P> <%= f.label :name %> <%= f.text_field :name %> </P>
<P> <%= f.label :quantity %> <%= f.text_field :quantity %> </P>
<P> <%= f.label :price %> <%= f.text_field :price %> </P>
<%= f.fields_for :images do |p| %>
<p> <%= p.label :photo %> <%= p.file_field :photo %> </p>
<%= p.link_to_remove "Remove Image" %>
<% end %>
<%= f.link_to_add "Add Image", :images %>
<%= f.submit "Add Product" %>
<% end %>
20160725102038_add_image_columns_to_imageable.rb:
class AddImageColumnsToImageable < ActiveRecord::Migration[5.0]
def up
add_attachment :images, :photo
end
def down
remove_attachment :images, :photo
end
end
Model:product.rb
class Product < ApplicationRecord
has_one :variant
has_many :images, as: :imageable, dependent: :destroy
accepts_nested_attributes_for :images, allow_destroy: true
end
Model:image.rb
class Image < ApplicationRecord
belongs_to :imageable, polymorphic: true
has_attached_file :photo, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment :photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
end

In rails 5, belongs_to makes sure that the associated model must exist.
E.g In this polymorphic association, Image model has belongs_to :imageable and Product model has has_many :images.
So here in new.html.erb we are creating an image, but respective product not exist, so that's why error Image imageable must exist .
Solution
Add optional: true while making an association of belong_to in Image model.
Image Model now looks like:
class Image < ApplicationRecord
belongs_to :imageable, polymorphic: true, optional: true
has_attached_file :photo, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment :photo, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
end

Related

Simple_form issues

I have a problem with simple_form's associations.
Here are the models "linked"
class Contact < ApplicationRecord
belongs_to :state
end
class State < ApplicationRecord
CATEGORIES = [ "not-contacted", "on-going", "called"]
has_many :contacts
validates :category, inclusion: { in: CATEGORIES }
end
I have also a State seed with the three states above.
I'm creating the new form for a contact.
Controller :
def new
#contact = Contact.new
#states = State.all
end
def create
#contact = Contact.new(contact_params)
if #contact.save
redirect_to contact_path(params[:id])
else
render :new
end
end
View:
<%= simple_form_for(#contact) do |f| %>
<%= f.input :last_name, label: 'Nom' %>
<%= f.input :first_name, label: 'Prénom' %>
<%= f.input :number, label: 'Téléphone' %>
<%= f.input :email, label: 'Mail' %>
<%= f.input :address, label: 'Adresse' %>
<%= f.association :state, collection: State.order(:category), prompt: "Choisir un état" %>
<%= f.input :grade, label: 'Note', collection:[1, 2, 3, 4, 5] %>
<%= f.submit 'Créer le contact', class:'btn-modifications' %>
<% end %>
But I have a collection not with a list of "on-going", "called", "not-contacted" but I have a list with this:
State:0x00007fcb3afcfca8
How can I display the list I want?
You need to change it to below
<%= f.association :state, collection: State.order(:category), label_method: :category, value_method: :id,prompt: "Choisir un état" %>

Access polymorphic attribute in the view

Trying to work out this small issue, I have finally got my polymorphic association working but now cant seem to figure out how to show an image in the view once a record has been saved.
My setup
class Image < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
attr_accessible :photo
has_attached_file :photo, :styles => { :small_blog => "250x250#", :large_blog => "680x224#", :thumb => "95x95#" }
end
class Post < ActiveRecord::Base
has_many :images, as: :imageable
accepts_nested_attributes_for :images
attr_accessible :comments, :title, :images_attributes
end
So in my view i have this at the moment, which is throwing undefined method 'photo' error
<% #posts.each do |p| %>
<%= image_tag(p.photo.url(:large_blog), :class => 'image') %>
<% end %>
Any pointers appreciated
Post has many images, and each image has a photo. So it can go like this:
<% #posts.each do |p| %>
<% p.images.each do |i| %>
<%= image_tag(i.photo.url(:large_blog), :class => 'image') %>
<% end %>
<% end %>

NoHandlerError Paperclip on ruby on rails 3.2.1

I am trying to make available to upload a multiple pictures with paperclip. I am following this tutorial: http://www.emersonlackey.com/article/paperclip-with-rails-3
Unfortunately I have error:
No handler found for "apple_mac-1280x800.jpg"
Asset.rb
class Asset < ActiveRecord::Base
belongs_to :post
has_attached_file :asset, :styles => { :small => "100x100", :original => '800x600>'}
end
Post.rb
class Post < ActiveRecord::Base
has_many :assets
accepts_nested_attributes_for :assets, :allow_destroy => true
end
Posts_controller.rb
def new
#post = Post.new
5.times { #post.assets.build }
respond_to do |format|
format.html # new.html.erb
format.json { render json: #post }
end
end
def edit
#post = Post.find(params[:id])
5.times { #post.assets.build }
end
#Post form
<% create_url = {:url=>{:action=>"create"}} if #post.new_record? %>
<% form_for #post, :html => {:multipart => true} do |t| %>
<p>
<%= t.label :title, 'Virsraksts:' %>
<%= t.text_field :title %>
</p>
<p>
<%= t.label :content, 'Teksts:' %>
<%= t.text_area :content, :class => "mceEditor"%>
</p>
<%= t.fields_for :assets do |asset_fields| %>
<% if asset_fields.object.new_record? %>
<p>
<%= asset_fields.file_field :asset %>
</p>
<% end %>
<% end %>
<%= t.submit %>
<% end %>
<%end%>
Problem solved by changing
<%= t.fields_for :assets do |asset_fields| %>
to
<%= f.fields_for :assets do |asset_fields| %>
But could someone explain why?

Nested Form Doesn't Save Nested Model Rails 3

I am trying to create a form that creates a game and game_players at the same time.
The problem I am having is that when I submit the form, the game is created, but the game_players are not.
I've looked around, but haven't found any helpful answers.
Game Model
class Game < ActiveRecord::Base
belongs_to :league
has_many :game_players, :dependent => :destroy
accepts_nested_attributes_for :game_players
attr_accessible :league_id, :game_date
validate :league_id, :presence => true
end
Game_Player Model
class GamePlayer < ActiveRecord::Base
belongs_to :game
has_many :users
validate :game_id, :presence => true
validate :user_id, :presence => true
end
Game Controller
class GamesController < ApplicationController
def new
#title = "New Game"
#game = Game.new
3.times { #game.game_players.build }
end
def create
#game = Game.new(:league_id => cookies[:league_id])
if #game.save
flash[:success] = "Succesfully Created Game"
redirect_to League.find_by_id(cookies[:league_id])
else
#title = "New Game"
render 'new'
end
end
Form
<%= form_for #game do |f| %>
<%= f.fields_for :game_players do |builder| %>
<p>
<%= builder.label :user_id, "User" %><br />
<%= builder.text_field :user_id %><br />
</p>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
most likely you need to pass :game_players_attributes to attr_accessible since .new respect mass-assignment security

accepts_nested_attrinutes_for rails3.1rc4

I use accepts_nested_attributes_for in a model but my child form isn't saved in the database?
I am building a nested form almost in the same way as in episode 196 / 197 from Ryan Bates railscasts. I have a parent question form and as a child the answer form:
models/question.rb
class Question < ActiveRecord::Base
belongs_to :user
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:text].blank? },
:allow_destroy => true
validates :content, :presence => true
end
models/answer.rb
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :user
end
controllers/questions_controller.rb
class QuestionsController < ApplicationController
before_filter :authenticate_user!
def index
setup_questions
end
def create
#question = Question.new(params[:question])
#this is to get every id_key from the user into the params of the answer
params[:question][:answers_attributes].keys.each {|key| params[:question][:answers_attributes][key][:user_id] = current_user.id }
#question.user_id = current_user.id
if #question.save
redirect_to questions_path, :notice => "Successfully created question."
else
setup_questions
render :index
end
end
def edit
#question = Question.find(params[:id])
end
def update
#question = Question.find(params[:id])
respond_to do |format|
if #question.update_attributes(params[:question])
format.html { redirect_to(#question, :notice => 'Question was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #question.errors, :status => :unprocessable_entity }
end
end
end
def show
#question = Question.find(params[:id])
end
def destroy
#question = Question.find(params[:id])
#authorize! :destroy, #question
#question.destroy
redirect_to questions_path, :notice => "Successfully deleted question: #{#question.content}."
end
private
def setup_questions
#questions = Question.all
#question ||= Question.new
#question.answers.build #to build the answers form
end
end
views/question/_form.html.erb
<%= form_for(#question) do |f| %>
<!-- =================== -->
<!-- = Error handeling = -->
<% if #question.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#question.errors.count, "error") %> prohibited this question from being saved:</h2>
<ul>
<% #question.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<!-- =================== -->
<!-- ================= -->
<!-- = Question form = -->
<div class="field">
<%= f.label :content, "Question" %><br />
<%= f.text_field :content, :placeholder => "type your question here.." %>
</div>
<!-- ====================== -->
<!-- = Nested Answer form = -->
<div class="answer-field">
<%= f.fields_for :answers do |builder| %>
<%= builder.label :content, "Possible answer" %><br />
<%= builder.text_field :content, :placeholder => "type an optional answer.." %>
<% end %>
</div>
<!-- ====================== -->
<div class="actions">
<%= f.submit %>
</div>
<!-- ================= -->
<% end %>
So now the big question... Why doesn't it save anything from the answer field to the database? I thought one create action at the parent (question) should be enough and that the "accepts_nested_attributes_for" should take care of it's child(s).
Regards,
Thijs
1 Remove this line from controller
params[:question][:answers_attributes].keys.each {|key| params[:question][:answers_attributes][key][:user_id] = current_user.id }
2 add this into your view
<!-- = Nested Answer form = -->
<div class="answer-field">
<%= f.fields_for :answers do |builder| %>
<% builder.object.user = current_user %>
<%= builder.label :content, "Possible answer" %><br />
<%= builder.text_field :content, :placeholder => "type an optional answer.." %>
<%= builder.hidden_field, :user_id %>
<% end %>
</div>
<!-- ====================== -->

Resources