jeudi 25 février 2016

Conditional nested form with simple_fields_for

I have a problem with creating two different forms with one model on one page. I tried two different approaches. Neither of them works.

Approach one:

Models:

class User < ActiveRecord::Base
  belongs_to :report

  ADMIN = 0
  NORMAL = 1
end

class Report < ActiveRecord::Base
  has_many :users
  has_many :normal_users, class_name: 'User', condition: {kind: User::NORMAL}
  has_many :admin_users, class_name: 'User', condition: {kind: User::ADMIN}
end

Approach 2 (Single Table Inheritance):

class User < ActiveRecord::Base
  belongs_to :report
end

class NormalUser < User
end

class AdminUser < User
end

class Report
  has_many :users
  has_many :normal_users
  has_many :admin_users
end

The problem:

simple_fields_for can see :users association:

= form_for @report do |f|
  = f.simple_fields_for :users do |ff|
    = ff.input :field_1
    = ff.input :field_2
  = f.submit 'Save'

But can't neither of :normal_users and :admin_users in both approaches.

= form_for @report do |f|
  = f.simple_fields_for :normal_users do |ff|
    = ff.input :field_1
    = ff.input :field_2
  = f.submit 'Save'

= form_for @report do |f|
  = f.simple_fields_for :admin_users do |ff|
    = ff.input :field_1
    = ff.input :field_2
  = f.submit 'Save'

By 'can't see' I mean you can write anything instead if :normal_users or :admin_users and the result is the same - one new record built like the association would not exist.

For now I can see only one option: To physically separate AdminUser and NormalUser by creating respective tables.

Are there other options. Where is the problem with conditional nested association within a form?

rails version 3.2.22

simple_form version 1.5.2

Aucun commentaire:

Enregistrer un commentaire