Using ActiveAdmin with Rails 4, I have two models, Document and Attachment with a one-to-many relationship between them.
# models/document.rb
class Document < ActiveRecord::Base
has_many :attachments
accepts_nested_attributes_for :attachments
end
# models/attachment.rb
class Attachment < ActiveRecord::Base
belongs_to :document
end
I registered the models and included permit_params for all the fields in each.
Now I used has_many in the form view in the below code. This shows an option to add Attachments and it work just fine.
# admin/document.rb
ActiveAdmin.register Document do
permit_params :title, :description, :date, :category_id
show do |doc|
attributes_table do
row :title
row :description
row :attachments do
doc.attachments.map(&:document_path).join("<br />").html_safe
end
end
end
form do |f|
f.inputs "Details" do
f.input :title
f.input :description
f.input :category
f.has_many :attachments, :allow_destroy => true do |cf|
cf.input :document_path # which is a field in the Attachment model
end
end
f.actions
end
end
However, when I submit the form, the document object is saved but no attachment objects are saved with it. As much as I understand it should create as many attachments I added in the form and pass in their document_id attribute the created document ID. Unfortunately this is not happening leaving the Attachment row "EMPTY" in the show view. Am I missing something?
Thanks in advance.
You forgot to permit attachments_attributes.
In order to use accepts_nested_attribute_for with Strong Parameters, you will need to specify which nested attributes should be whitelisted.
More info http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html
Related
I am using ActiveAdmin in my rails application.My setup is the following:
app/models/translation_type.rb
class TranslationType < ActiveRecord::Base
has_many :translation_details
accepts_nested_attributes_for :translation_details, allow_destroy: true
end
app/models/translation_detail.rb
class TranslationDetail < ActiveRecord::Base
belongs_to :translation_type
attr_accessor :id, :language_from, :language_to, :price
end
app/admin/translation_type.rb
ActiveAdmin.register TranslationType do
permit_params :translation_type, translation_details_attributes: [:id, :language_from, :language_to, :price, :_destroy]
index do
column :translation_type
column :translation_details
column :created_at
column :updated_at
actions
end
filter :translation_type
filter :created_at
form do |f|
f.inputs "Translation Type Details" do
f.input :translation_type
f.input :created_at
f.input :updated_at
end
f.inputs do
f.has_many :translation_details, allow_destroy: true do |tran_det|
tran_det.input :language_from, :collection => ['Gr', 'En', 'Fr', 'De']
tran_det.input :language_to, :collection => ['Gr', 'En', 'Fr', 'De']
tran_det.input :price
end
end
f.actions
end
controller do
before_filter { #page_title = :translation_type }
end
I don't need a section for translation_detail so I have omited app/admin/translation_detail.rb
I want to have nested forms of translation_detail in my translation_type form. Using the code above creates the nested form but after submit the attributes of translation_detail are not saved. Furthermore when I try to update or delete a translation_detail this message is shown
Couldn't find TranslationDetail with ID=* for TranslationType with ID=*
How can this be fixed?
It seem that this line
attr_accessor :id, :language_from, :language_to, :price
in app/models/translation_detail.rb, was causing the error, but I am not really sure why.
I ran into the same problem when saving a field that previously wasn't being saved and did not exist in the DB. I had to remove the attr_accessor :fieldName from the model file to make it permanent.
As this answers states: attr_accessor on Rails is only ever used if you don't want the attributes to be saved to the database, only stored temporarily as part of an instance of that Model.
What probably was happening in the question's example is that it could not save the TranslationDetail because everything except for its relationship to TranslationType was being discarded before saving.
Imagine I have the following models:
class Translation < ActiveRecord::Base
has_many :localizations
end
class Localization < ActiveRecord::Base
belongs_to :translation
end
If I do this in ActiveAdmin:
ActiveAdmin.register Localization do
form do |f|
f.input :word
f.input :content
end
end
The association for word will only allow me to choose from existing words. However, I'd like to have the option of creating a new word on the fly. I thought it may be useful to accept nested attributes in the localization model ( but then, I will only have the option of creating a Word, not selecting from existing ones ). How can I solve this problem?
I think you can try using virtual attribute for this
Example(not tested)
class Localization < ActiveRecord::Base
attr_accessor :new_word #virtual attribute
attr_accessible :word_id, :content, :new_word
belongs_to :translation
before_save do
unless #new_word.blank?
self.word = Word.create({:name => #new_word})
end
end
end
The main idea is to create and store new Word instance before saving localization and use it instead of word_id from drop-down.
ActiveAdmin.register Localization do
form do |f|
f.input :word
f.input :content
f.input :new_word, :as => :string
end
end
There is great rails-cast about virtual attributes http://railscasts.com/episodes/167-more-on-virtual-attributes
So here's the Thing:
I have a Rails App with "Productos" and "Ventas" Both resources have the same attributes on their tables and ventas has one more (quantity)... the models look like this:
#Producto Model
class Producto < ActiveRecord::Base
has_and_belongs_to_many :categorias, :join_table => :categoria_productos
attr_accessible :color, :existencia, :nombre, :precio, :talla, :uniclave, :categoria_ids
#Venta Model
class Venta < ActiveRecord::Base
attr_accessible :cantidad, :color, :nombre, :precio, :talla, :uniclave, :producto_ids
has_many :productos
end
I'm using ActiveAdmin for the Admin interface and my /admin/venta.rb looks like this:
ActiveAdmin.register Venta do
form do |f|
f.inputs "Registrar Venta" do
f.input :cantidad
f.input :productos, :as => :check_boxes
end
f.buttons
end
end
The result is ALL THE PRODUCTOS are showing in the "new venta" form and I can select them, but when I create a new Venta actually, the params of "venta" save empty instead of taking the selected "producto" ones...
How can I fix this?? I want all the params of the selected "producto" to be used in the newly created "venta" fields as they share the same attributes (both models have been created with the same attributes actually)
So, ideas? ;)
:categoria_ids and : producto_ids must be as :categoria_id and :producto_id OR you must use the :foreign_key for behavior between models
I have the models Home and Photo, which have a has_many - belongs_to relationship (a polymorphic relationship, but I dont think that matters in this case). I am now setting up active admin and I would like admins to be able to add photos to homes from the homes form.
The photos are managed by the CarrierWave gem, which I dont know if will make the problem easier or harder.
How can I include form fields for a different model in the Active Admin Home form? Any experience doing something like this?
class Home < ActiveRecord::Base
validates :name, :presence => true,
:length => { :maximum => 100 }
validates :description, :presence => true
has_many :photos, :as => :photographable
end
class Photo < ActiveRecord::Base
belongs_to :photographable, :polymorphic => true
mount_uploader :image, ImageUploader
end
Try something like this in app/admin/home.rb:
form do |f|
f.inputs "Details" do
f.name
end
f.has_many :photos do |photo|
photo.inputs "Photos" do
photo.input :field_name
#repeat as necessary for all fields
end
end
end
Make sure to have this in your home model:
accepts_nested_attributes_for :photos
I modified this from another stack overflow question: How to use ActiveAdmin on models using has_many through association?
You could try this:
form do |f|
f.semantic_errors # shows errors on :base
f.inputs # builds an input field for every attribute
f.inputs 'Photos' do
f.has_many :photos, new_record: false do |p|
p.input :field_name
# or maybe even
p.input :id, label: 'Photo Name', as: :select, collection: Photo.all
end
end
f.actions # adds the 'Submit' and 'Cancel' buttons
end
Also, you can look at https://github.com/activeadmin/activeadmin/blob/master/docs/5-forms.md (See Nested Resources)
I guess you are looking for a form for a nested model. Take a look at following railscasts.
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
I cannot tell you much about active_admin, but I think this should not make a difference in handling the nested model.
I have a has_one model, like this:
f.has_many :addresses do |a|
a.inputs "Address" do
a.input :street ... etc.
While this correctly reflects our associations for Address (which is a polymorphic model) using f.has_one fails. So I changed over to has_many and all's well. Except now we have to prevent our users from creating multiple addresses for the same entity.
We are using active_admin for our administration backend.
We have a model "App" that :belongs_to model "Publisher":
class App < ActiveRecord::Base
belongs_to :publisher
end
class Publisher < ActiveRecord::Base
has_many :apps
end
When creating a new entry for the "App" model I want to have the option to either select an existing publisher or (if the publisher is not yet created) to create a new publisher in the same (nested) form (or at least without leaving the page).
Is there a way to do this in active_admin?
Here's what we have so far (in admin/app.rb):
form :html => { :enctype => "multipart/form-data" } do |f|
f.inputs do
f.input :title
...
end
f.inputs do
f.semantic_fields_for :publisher do |p| # this is for has_many assocs, right?
p.input :name
end
end
f.buttons
end
After hours of searching, I'd appreciate any hint... Thanks!
First, make sure that in your Publisher model you have the right permissions for the associated object:
class App < ActiveRecord::Base
attr_accessible :publisher_attributes
belongs_to :publisher
accepts_nested_attributes_for :publisher, reject_if: :all_blank
end
Then in your ActiveAdmin file:
form do |f|
f.inputs do
f.input :title
# ...
end
f.inputs do
# Output the collection to select from the existing publishers
f.input :publisher # It's that simple :)
# Then the form to create a new one
f.object.publisher.build # Needed to create the new instance
f.semantic_fields_for :publisher do |p|
p.input :name
end
end
f.buttons
end
I'm using a slightly different setup in my app (a has_and_belongs_to_many relationship instead), but I managed to get it working for me. Let me know if this code outputs any errors.
The form_builder class supports a method called has_many.
f.inputs do
f.has_many :publisher do |p|
p.input :name
end
end
That should do the job.
Update: I re-read your question and this only allows to add a new publisher, I am not sure how to have a select or create though.
According to ActiveAdmin: http://activeadmin.info/docs/5-forms.html
You just need to do as below:
f.input :publisher
I've found you need to do 3 things.
Add semantic fields for the form
f.semantic_fields_for :publisher do |j|
j.input :name
end
Add a nested_belongs_to statement to the controller
controller do
nested_belongs_to :publisher, optional: true
end
Update your permitted parameters on the controller to accept the parameters, using the keyword attributes
permit_params publisher_attributes:[:id, :name]