How do you delete images in ActiveAdmin form? - ruby-on-rails

I currently have a HABTM relationship between art and art_pic_attachment (which are images). No problem in creating objects but when I want to delete an image - I can't find any clean documentation that shows how to delete an image. I've tried the _destroy option but nothing happens. Any clue how to fix this?
ActiveAdmin.register Art do
permit_params :art_pic_attachments_attributes: [:id, :picture, :_destroy]
form(html: { multipart: true }) do |f|
f.inputs do
f.has_many :art_pic_attachments, allow_destroy: true, heading: 'Images' do |ff|
ff.file_field :picture, required: true, heading: "Pictures"
end
end
f.actions
end
Model:
class Art < ApplicationRecord
has_many :art_pic_attachments, dependent: :destroy
accepts_nested_attributes_for :art_pic_attachments, allow_destroy: true
end

This wiki article discusses how to do this with Paperclip and overriding <attachment_name>_attributes=, eg.
def attachment_attributes=(attributes)
attachment.clear if has_destroy_flag?(attributes) && !attachment.dirty?
end

Related

Rails activeadmin save data in associated table

I have one table for Products and the product can either be in the interior or exterior or both. So I created another table to save the Products location. Now when admin adds the product I have provided the option to select the location(s) the product can be in, but when it is posted the code says the field can't be blank because of the validation. I am not sure what I am missing or the approach is wrong.
The product model:
class Product < ApplicationRecord
validates :name, presence: true
has_many :product_locations
accepts_nested_attributes_for :product_locations
end
The product location model:
class ProductLocation < ApplicationRecord
enum locations: [:exterior, :interior]
validates :location, presence: true
validates :product_id, presence: true
belongs_to :product
end
The ActiveAdmin file for Product:
ActiveAdmin.register Product do
permit_params :name, product_locations_attributes: {}
actions :all, except: [:show, :destroy]
filter :name
index do
column 'Product Name', :name
actions
end
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs "Products" do
f.input :name
end
f.has_many :product_locations do |location|
location.inputs "Locations" do
location.input :location, as: :select, multiple: true, collection: ProductLocation.locations.keys
end
end
f.actions
end
controller do
def scoped_collection
Product.where(user_id: nil)
end
end
end
I get a multi-select for the locations which has "Interior" and "Exterior" for selection, but it says the field can't be blank when I select the location and submit the form
The error on save click I get is:
Location can't be blank
The params that get posted are:
Parameters: {"utf8"=>"✓", "product"=>{"name"=>"Test Product", "product_locations_attributes"=>{"0"=>{"location"=>["0", "1"]}}}, "commit"=>"Create Product"}
First, the permit attributes should be,
product_locations_attributes: [:id, :location]
Then, in your form
location.input :location, as: :select, multiple: true, collection: ProductLocation.locations.keys
Since ProductLocation.locations is an array, array.keys is an invalid method.
So, use directly
location.input :location, as: :select, multiple: true, collection: ProductLocation.locations.map { |n| [n,n] }
To store an array of multiple values take serialize field as an array,
class ProductLocation < ApplicationRecord
enum locations: [:exterior, :interior]
serialize :location, Array
validates :location, presence: true
validates :product_id, presence: true
belongs_to :product
end
Note: Inorder to get the serialize work, you need to have the dataType of the location as a text. If it is not text run a migration to change to text data type
Reason for text field: Rails will convert all those object into plain text when storing in database

Rails - activeadmin, duplicating has_many records upon updating "parent" record

My models are as follows:
class Project < ActiveRecord::Base
has_many :project_images
accepts_nested_attributes_for :project_images
end
class ProjectImage < ActiveRecord::Base
belongs_to :project
mount_uploader :image, ImageUploader
end
Here's the activeadmin file:
ActiveAdmin.register Project do
remove_filter :projects_sectors
permit_params :title, :info, :case_study, project_images_attributes: [:image, :cover]
index do
column :title
actions
end
form :html => { :enctype => "multipart/form-data" } do |f|
f.inputs "Project" do
f.input :title
f.input :info
f.input :case_study, :as => :file
end
f.inputs "Images" do
f.has_many :project_images, :allow_destroy => true, :heading => false, :new_record => true do |img_f|
img_f.input :image, :as => :file , :hint => f.template.image_tag(img_f.object.image)
img_f.input :cover
end
end
f.actions
end
end
The problem is that when i simply edit a project and click on update project, it simply duplicates all the records that exist for relationship at that point. Eg. if i have 2 images under 1 project, after changing say, the project title, i will end up with 4 images.
Hope it's clear what the issue is. Would appreciate greatly if anybody could give me a litle help.
Thanks a lot in advance.
You have to permit the id of the images: project_images_attributes: [:id, :image, :cover]
If you don't permit the id, it will be null in the action, and rails thinks it's a new record and save it.
I think this is the same problem as this one discussed on the CarrierWave wiki. Instead of generating input fields for existing images, generate an image tag and a 'remove?' option. If you generate an input field for them, then you'll end up with duplicate results.
ActiveAdmin.register Project do
controller do
def apply_filtering(chain)
super(chain).distinct
end
end
# your code
end

Active Admin Rails 4 has many

I am working with Rails 4, Active Admin and Paperclip to setup a has_many images association. When generating my has_many portion of the form I keep getting errors. Currently I am getting
undefined method `+' for nil:NilClass. Here is my code:
news model
class News < ActiveRecord::Base
validates :body, presence: true
validates :title, presence: true, length: { maximum: 140 }
has_many :news_images, dependent: :destroy
end
News image model
class NewsImage < ActiveRecord::Base
belongs_to :news
has_attached_file :photo, styles: {
small: "150x150>",
medium: "300x300>",
large: "600x600>"
}
validates_attachment_presence :photo
validates_attachment_size :photo, less_than: 5.megabytes
end
admin code
ActiveAdmin.register News do
index do
column :title
default_actions
end
form multipart: true do |f|
f.semantic_errors *f.object.errors.keys
f.inputs "News Details" do
f.input :title
f.input :body, :as => :rich
end
f.has_many :news_images do |p|
end
f.actions
end
controller do
def permitted_params
params.permit news: [:title, :body, news_images: [:photo]]
end
end
end
Ideally I would like the user to be able to upload multiple images to the form. Any one have experience with this issue?
The stack trace is saying insert_tag renderer_for(:new) which is being tripped on f.has_many :news_images do |p|
So the problem was with the news model. I thought accepts_nested_attributes_for was deprecated with the addition of strong params but I guess I was wrong adding this to the news model fixed my issue
accepts_nested_attributes_for :news_images,
:reject_if => lambda { |attributes| attributes[:photo].blank? },
:allow_destroy => true
There was another bug in Paperclip 4.1 that was fixed recently: https://github.com/thoughtbot/paperclip/issues/1457
I spent a ton of time tracking this down, but finally was able to find the connection between formtastic and paperclip 4.1.
The solution that worked for me was to switch to paperclip's master branch in my Gemfile as follows:
gem 'paperclip', github: 'thoughtbot/paperclip'

validation and accepts_nested_attributes_for

i have two models :
class Article < ActiveRecord::Base
belongs_to :league
has_many :photos, :dependent => :destroy
attr_accessible :content, :lead, :title, :title_slug,
:created_at, :updated_at,
:league_id, :photos_attributes
accepts_nested_attributes_for :photos
validates :content, :league, :presence => true
validates :lead , :length => {maximum: 1000}, :presence => true
validates :title ,:length => {maximum: 200}, :presence => true
validates_associated :photos
and
class Photo < ActiveRecord::Base
belongs_to :article
attr_accessible :photo
validates :photo, presence: true
has_attached_file :photo , :styles => { :medium => '440x312#', :small => '209x105!'}
end
My ArticlesController is
...
def new
#article = Article.new
#article.photos.build
end
def create
#article = Article.new(params[:article])
if #article.save
redirect_to([:admin,#article])
else
render 'new'
end
end
...
form view is :
= form_for([:admin,#article] , :html => {:multipart => true}) do |f|
- if #article.errors.any?
= render 'errors'
= f.fields_for :photos do |builder|
= builder.label :photo
= builder.file_field :photo
...
i have some question about it :
1) I dont want to save an article without empty photo but now when i dont choose a file my article saves.
2) When i have some errors on article's fields and render 'new' ,my photo field dissapear , what is the rails way to resolve it.
3) in the future i want to add another model: photo_type and assosciate it with photo. Each article will have two photo fields , each with own type (for example: small , big) . I wonder how to render that fields and what can i do to save article with two photos with different types.
Answer for 1: Use validates_associated :photos. Documentation
Answer for 2: I guess that is an file attachment field. For that, this is generally done by setting up a hidden cache field and by using some callbacks. MountUploader uses the same principle.
Answer for 3: Little skeptical, but I guess something will work along this way:
In your Article model, have two associations with Photo as:
has_one :small_photo, :class_name => "Photo"
has_one :big_photo, :class_name => "Photo"
This will enable you to have two sub-form fields present for both types while opening up the form for Article.
Hope it helps. Do comment if last one can work for you in this way. It looks like the good deal to me :)

Rails 3 association error: undefined method

I've been puzzling over this for quite some time now and can't figure it out.
I've got 2 models:
class Vehicle < ActiveRecord::Base
attr_accessible :year, :capacity,
:size, :body, :model_id, :maker_id, :parameters_attributes
validates :year, numericality: { greater_than: 1900 }
validates :year, :capacity, :size, :body, presence: true
belongs_to :model
belongs_to :maker
has_many :parameters
accepts_nested_attributes_for :parameters
end
and
class Parameter < ActiveRecord::Base
attr_accessible :tag, :value
validates :tag, :value, presence: true
belongs_to :vehicle
end
in new vehicle view i've got:
= form_for [:admin, #vehicle], html: { multipart: true } do |f|
=# some other stuff in between
= f.text_field :value, size: 4
I get this error
undefined method `value'
Just can't seem to get it working. Help, anyone?
EDIT
routes.rb
resources :vehicles
resources :parameters
resources :makers do
resources :models
end
If you are using nested form, you should have something like
f.fields_for :parameters do |parameter|
and than:
parameter.text_field :value, size: 4
Also, remember to create the some parameters in the controller, for example:
def new
#vehicle = Vehicle.new
2.times { #vehicle.parameters.build } #it will create 2 parameters
...
end
f refers to #vehicle, it seems only Parameter bears this field. That's why it fails.
Sidenotes:
In Vehicle you have accepts_nested_attributes_for :parameters but you don't have parameters_attributes in the attr_accessible, can't be good.
If you want to call the relationship in the form consider using fields_for
Ok, I've made a mess of things.
Firstly I've been trying to
def new
#vehicle = #vehicle.parameters.build
end
hence the error undefined method. After a while I got to the correct syntax, which is the one gabrielhilal added after a while.
def new
#vehicle = Vehicle.new
#vehicle.parameters.build
end
No matter ;) Still had problems, because after clicking "create" he wouldn't add records in the database. Turned out that I've set the validates presence: true for tag, but didn't assign any value to it. After fixing that, it worked like a charm. Thanks a lot for all the help.
On to the next puzzle.

Resources