New Discussion

Notifications

You’re not receiving notifications from this thread.

How do I update a model with has_many :through association in grouped_collection_select

0
Rails

I have the following models:

class User < ApplicationRecord
  self.table_name = 'user.users'
  has_many :user_sources
  has_many :sources, through: :user_sources, foreign_key: :source_code
end

class User::Source < ApplicationRecord
    self.table_name = 'user.sources'
        self.primary_key = 'code'
        has_many :user_sources, foreign_key: :source_code
        has_many :users, through:  :user_sources
end

class User::UserSource < ApplicationRecord
    self.table_name = 'user.user_sources'
    belongs_to :user
    belongs_to :source, foreign_key: :source_code
    belongs_to :category,   class_name: 'User::SourceCategory',   foreign_key:  :category_code, inverse_of: :sources
    validates :user, :source, presence: true
end

class User::SourceCategory < ApplicationRecord
  self.table_name = 'user.source_categories'
  self.primary_key = 'code'
  has_many :sources,   foreign_key: :category_code,  inverse_of: :category
  validates :code, :name, presence: true, uniqueness: true
end

I have the following form (using slim html):

            form_for(user, multipart: true) do |f|
                    ...
                    ....
                  .form-group
                            = f.label :sources, "Source"
                            = f.grouped_collection_select(:sources,  User::SourceCategory.order(name: :asc), :sources, :name, :code, :name, \
                                    {prompt: true}, {class: 'form-control', required: true})    

In controller#new, i also did something like this:

    @user.sources.build
    @user.user_sources.build

I am not sure if I have set the grouped_collection_select correctly, but the @user.sources didn't have any value upon create. And yes I did permit the parameters as well. I am not sure how to configure the form so that upon submit the form, the @user.sources will be updated correctly based on the grouped_collection_select input selected. Not sure if i am missing something. Appreciate if anyone could guide/advise me on the right way to implement this.

Join the discussion
Create an account Log in

Learning Ruby on Rails? Join our newsletter.

We won't send you spam. Unsubscribe at any time.