I have 3 models:
class Resource < ActiveRecord::Base
has_many :blocks
has_many :topics, :through => :blocks, dependent: :destroy
class Topic < ActiveRecord::Base
has_many :blocks
has_many :resources, :through => :blocks, :class_name => 'Resource', dependent: :destroy
accepts_nested_attributes_for :resources
accepts_nested_attributes_for :blocks, :allow_destroy => true
class Block < ActiveRecord::Base
belongs_to :resource
belongs_to :topic
accepts_nested_attributes_for :resource, :allow_destroy => true, :reject_if => :all_blank
My routes:
namespace :admin do
resources :topics do
resources :resources do
post :link
delete :unlink
Everything works fine except that I'd like to have in the "Add resource" a way to select an existing resource (in a drop down) in addition to create a new one (which works fine).
So, I'd like a drop down showing all the resources, then adding the one I selected to the Block model. In other words, I need to only create the association between the topic and the ressource (via the Block model).
I'm able to do it when I have all a multi-select but I'm banging my head to have it available with one resource only (adding it on the ones already selected).
Am I clear? :/
Thanks! - Vincent
If you got a complicated logic like this, it's better to use something like "Form Objects" to save multiple models and relations between them. I.e. move saving logic outside of both models.
access_nested_attributes_for
should be used only for very very simple cases (like most of Rails's magical features)