Question

I have a nested model form, my Foo has many Bars and Baz has many Bars

Foo.rb

has_many :bars
accepts_nested_attributes_for :bars

Bar.rb

belongs_to :Foo
belongs_to :Baz

Baz.rb

has_many :bars

views/foos/_form.html.haml

= f.simple_fields_for :bars do |p|
   = render "bar_fields", f: p

When I bring up the form to edit, I would like to disable the editing of a particular Bar if it belongs to a certain Baz.

For each of the bars that it renders, how do I check within the view, what the value is of a certain attribute. In this case, what the value of Baz is in the Bar record.

Was it helpful?

Solution

views/foos/_form.html.haml

= f.simple_fields_for :bars, @foo.bars.not_belonging_to_a_certain_baz(baz_id) do |p|
   = render "bar_fields", f: p

Bar.rb

scope :not_belonging_to_a_certain_baz, ->{ |baz_id| where("bars.baz_id != ?", baz_id) }

Or if you are not able to use scope, you can check each bar separatly when render bar_fields partial:

views/foos/_form.html.haml

= f.simple_fields_for :bars, do |p|
   = render "bar_fields", f: p if p.object.baz_id != baz_id

OTHER TIPS

I found something similar and here's what I did

_form.html.haml

= f.simple_fields_for :bars do |p|
    - if f.object.baz_id == baz_id
        = render "bar_fields", f: p
    - else
        = render "bar_fields_readonly", f: p
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top