How can the association between my two models be saved in ActiveAdmin?
I have two models a room and a photo model. In the ActiveAdmin I want to update the association between the photo and the room.
room.rb (app/models)
class Room < ApplicationRecord
has_many :photos
accepts_nested_attributes_for :photos
end
photo.rb (app/models)
class Photo < ApplicationRecord
belongs_to :room
has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end
photo.rb (app/admin)
ActiveAdmin.register Photo do
permit_params :image, , rooms_attributes: [:id, :listing_name, :room_id, :photo_id, :images]
index do
selectable_column
id_column
column :image_file_name
column :listing_name
column :room
column :updated_at
column :created_at
actions
end
show do |image|
attributes_table do
row :image do
photo.image? ? image_tag(photo.image.url, height: '100') : content_tag(:span, "No photo yet")
end
end
active_admin_comments
end
form :html => { :enctype => "multipart/form-data" } do |f|
f.inputs do
f.input :image, hint: f.photo.image? ? image_tag(f.photo.image.url, height: '100') : content_tag(:span, "Upload JPG/PNG/GIF image")
end
f.inputs do
f.collection_select :room, Room.all,:id,:listing_name
end
f.actions
end
The form seems to work but it does not save it to the database when I check the record(last room) in the rails console it always returns me room_id: nil? I have tried everything nothing seems to work. Please help.
UPDATE
I have added, "rooms_attributes: [:id, :listing_name, :room_id, :photo_id, :images]" to the params in the photo.rb(admin). I have also have added :photo_id to the room.rb(admin) file.
But it still does not work! Any hints welcomed! If someone needs further information just let me know.
Try
permit_params :image, room_id
f.collection_select :room_id, Room.all, :id, :listing_name
Related
I use Active admin and I need upload photos for my project.
How can I do it? My code:
class Project < ApplicationRecord
has_many :images
accepts_nested_attributes_for :images
end
class Image < ApplicationRecord
belongs_to :project
has_attached_file :image
validates_attachment_presence :image
end
ActiveAdmin.register Project do
permit_params :project_name , :project_location , :project_status , :project_area , :project_prices , :project_info , :project_description , :image , :image_file_name, :image_content_type, :image_file_size, :image_updated_at
index do
column :project_name
column :project_description
actions
end
form :html => { :enctype => "multipart/form-data" } do |f|
f.inputs 'Project Info' do
f.input :project_name
f.input :project_description
end
f.inputs do
f.has_many :images do |p|
p.input :image , as: :file
end
end
f.actions
end
end
With this code i can create Project without image. But i can't add any image to db.
Waiting for help !!!
I solve the problem ! working code :
permit_params :project_name , :project_location , :project_status , :project_area , :project_prices , :project_info , :project_description , images_attributes: [:image , :id , :_destroy]
f.inputs do
f.has_many :images , heading: false, allow_destroy: true do |ff|
ff.input :image, required: true, as: :file
end
end
most important part that i miss is : images_attributes: [:image , :id , :_destroy] if you don't write this part fully , it won't work !
I am using activeadmin for car resource and multiple attachments are not entering into records, car records are created successfully but on creation it did not contain attachment. I have two models 'Attachment', models/attachment.rb
class Attachment < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" },default_url: "/images/:style/missing.png"
validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
end
And
and my model/car.rb contains following code
class Car < ActiveRecord::Base
has_many :attachments, as: :imageable
accepts_nested_attributes_for :attachments
end
and in my app/admin/car.rb I have following code for multiple attachment.
form do |f|
f.input :make
f.input :model
f.input :color
f.input :engine_type
f.input :description
f.has_many :attachments do |attachment|
attachment.input :attachment, :as => :file
end
f.actions
end
Can anybody please explain how to fix this issue?
I think your input field should be :avatar instead of :attachment
So, it should look like
f.has_many :attachments do |attachment|
attachment.input :avatar, :as => :file
end
I have menu model and photos model where the menu has has_many relationship with photo. For the image upload, I'm using paperclip. I was able to build a nested_form that creates photo and other attributes in photos table. However, when I update, the record gets duplicated in photos table and the new photo selected in the update form will not be uploaded. Appreciate your help.
menu model
class Menu < ActiveRecord::Base
has_many :photos, :dependent => :destroy
accepts_nested_attributes_for :photos, reject_if: :all_blank, allow_destroy: true
end
photo model
class Photo < ActiveRecord::Base
belongs_to :menu
has_attached_file :image,
:styles => { :thumb => "100x100#", :medium => "300x300#", :large => "600x400>" },
:url => "/assets/menus/photos/images/:id/:style/:basename.:extension",
:path => "#{Rails.root}/public/assets/menus/photos/images/:id/:style/:basename.:extension"
validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
end
form.html.haml
= simple_form_for #menu do |f|
= f.simple_fields_for :photos do |photo|
= render 'photo_fields', f: photo
_photo_field.html.haml
.nested-fields
= f.file_field :image
= f.input :main_flag, as: :hidden, input_html: { value: "true" }
= f.input :user_id, as: :hidden, input_html: { value: "1"}
menus_controller.rb
class MenusController < ApplicationController
...
def update
#menu = Menu.find(params[:id])
if #menu.update(menu_params)
if params[:image]
#menu.photos.destroy
#menu.photos.build(menu_params)
end
flash[:success]= 'Menu was successfully updated'
redirect_to brand_menus_path(#menu.brand_id)
else
render 'index'
end
end
private
def menu_params
params.require(:menu).permit(:name, :price, :brand_id, :category_id, :description,
photos_attributes: [:user_id, :image, :main_flag])
end
This is very common problem with the strong_parameters when using with nested_params. Whitelisting the :id in the photos_attributes should fix your problem
def menu_params
params.require(:menu).permit(:name, :price, :brand_id, :category_id, :description,
photos_attributes: [ :id, :user_id, :image, :main_flag])
end
I have a structure User-> Profile-> Image and want to use one form for editing and recording in ActiveAdmin.
I use accepts_nested_attributes_forin models:
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy;
accepts_nested_attributes_for :profile, allow_destroy: true
end
class Profile < ActiveRecord::Base
belongs_to :image, dependent: :destroy;
accepts_nested_attributes_for :image,:reject_if => proc { |attributes| !attributes['img'].present? }, :allow_destroy => true
end
class Image < ActiveRecord::Base
has_attached_file :img
validates_attachment_content_type :img, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
end
And such permit_params in ActiveAdmin.register User:
permit_params do
permitted=[:id,:login, :email, :admin, :password, :password_confirmation, :ip_address];
permitted.append(profile_attributes:[:name,:second_name,:middle_name,:img,:mobile_phone,:country, :city,:region, image_attributes:[:img]]);
permitted
end
Finally, the code itself forms
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs "User Details" do
f.input :login
f.input :email
f.input :password
f.input :password_confirmation
end
f.inputs "Profile", for: [:profile, f.object.profile || f.object.build_profile] do |pf|
pf.input :name
pf.input :second_name
pf.input :middle_name
pf.input :mobile_phone, :as => :phone
pf.input :country, selected: "RU"
pf.input :city
pf.input :region
pf.inputs "Avatar", for:[:image, pf.object.image || pf.object.build_image] do |fpf|
fpf.input :img, :as => :file
end
end
f.inputs "User Perference" do
f.input :admin, type: :boolean
end
f.actions
end
Unfortunately, this code does not work: the form is correctly displayed with Profile and work, but the form is not visible to the Image. How can I fix this?
Unfortunately, I have not found the right solution for this problem, and it is still relevant (I'm not going to close this question, just in case someday it will answer).
But I modeled the behavior close to the desired one.
So, to the User model I added Avatar-interface for the respective object.
def avatar
if self.profile && self.profile.image
self.profile.image.img
else
nil
end
end
def avatar=(arg)
unless self.profile.image
self.profile.create_image(img:arg)
else
self.profile.image.update_attributes(img:arg)
end
self.profile.image
end
def avatar?
if self.profile && self.profile.image
!self.profile.image.img.nil?
else
nil
end
end
In ActiveAdmin added to the avatar permit_params for User.
permit_params ..., :avatar
Finally, in the form of added file fields:
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs "User Details" do
#Fields for User
end
f.inputs "profile", for: [:profile, f.object.profile || f.object.build_profile] do |pf|
#Fields for profile
end
f.inputs "Avatar" do
f.input :avatar, as: :file
end
f.actions
end
It is worth noting that if you have observed abnormal behavior when the form is submitted, with empty values, then you should pay attention to the parameters for accepts_nested_attributes_for, in particular update_only and reject_if.
I'm still waiting for the normal solution for multiple nested forms in ActiveAdmin
I'm using Paperclip to let my users upload images.
It works pretty well with separated single resources. I can add, edit, and delete all images without any extra effort using a RESTFUL structure.
But I have some difficulties while working with nested attributes.
I have 2 models called Article and Headline.
I'm using an Article form in my view to create an associated instance of Headline. So I'm using accepts_nested_attributes_for with ActiveRecord. I've set up everything related to this. I'm using fields_for in my form view. Strong parameters settings are all done. Everything works great with adding a NEW article with its headline. I also have a title field which updates appropriately.
<%= f.fields_for :headline do |r| %>
<%= r.label :title %>
<%= r.text_field :title %>
<%= r.label :image, "Headline image" %>
<%= r.file_field :image %>
<% end %>
But when I UPDATE an article without any change of the Headline's image, the Headline's image disappears.
As I know and experience, Paperclip doesn't update image files unless they are changed. That's the expected behavior. But in this case, it overwrites the nested model's attribute even though it shouldn't.
I think there must be a workaround for this?
Article.rb:
class Article < ActiveRecord::Base
after_commit :expire_caches
scope :desc, ->{ order(created_at: :desc)}
scope :with_images, -> {where.not(image_file_name: nil)}
before_validation :set_default_category
acts_as_taggable
attr_accessor :is_headline
has_attached_file :image, default_url: "default_:style.png",
:styles => { :large=>"700", :medium => "296", :thumb => "150", mini_thumb: "50x50>", :absolute_thumb=>"150x150#" },
:s3_host_name => 's3-eu-west-1.amazonaws.com',
:path => "articles_images/:id/:style/:basename.:extension"
#validates :title, presence: true
belongs_to :category
belongs_to :user
validates :title, :content, presence: true
validates :content, length: {minimum: 10}
validates :category_id, presence: true
validates :cihan_url, uniqueness: true, allow_nil: true
has_many :galleries, dependent: :destroy
has_one :headline, dependent: :destroy
has_one :ad, dependent: :destroy
has_many :videos
accepts_nested_attributes_for :headline
def self.main_page
where(main_page: true).with_images.desc
end
def to_param
"#{self.id}-#{self.title.parameterize}"
end
private
def set_default_category
self.category = Category.uncategorized if self.category.blank?
end
def expire_caches
Rails.cache.clear
end
end
Headline.rb:
class Headline < ActiveRecord::Base
after_commit :expire_caches
has_attached_file :image, default_url: "default_:style.png",
:styles => { :large=>"600", :medium => "300x300>", :thumb => "150x150>", :absolute_thumb=>"150x150#" },
:s3_host_name => 's3-eu-west-1.amazonaws.com',
:path => "headline_images/:id/:style/:basename.:extension"
belongs_to :article
private
def expire_caches
Rails.cache.clear
end
end
From articles_controller:
def set_article
#article = Article.find(params[:id])
end
def update
if #article.update(article_params)
redirect_to [:admin, #article], flash: {success: "<i class=\"icon-ok\"></i> Haber başarıyla düzenlendi.".html_safe}
else
render action: 'edit'
end
end
def article_params
params.require(:article).permit(:title, :content, :publish_date, :category_id, :active, :tag_list, :main_page, :extra_title, :image, :is_headline, headline_attributes: [:title, :counter, :order, :image])
end