Rails:如何根据值进行只读输入

时间:2014-03-09 06:56:31

标签: ruby-on-rails ruby ruby-on-rails-4 simple-form

我有一个嵌套的模型表单,我的Foo有很多BarsBaz有很多Bars

Foo.rb

has_many :bars
accepts_nested_attributes_for :bars

Bar.rb

belongs_to :Foo
belongs_to :Baz

Baz.rb

has_many :bars

视图/ FOOS / _form.html.haml

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

当我打开要编辑的表单时,如果某个Bar属于某个Baz,我想禁用其编辑。

对于它呈现的每个bars,如何在视图中检查某个属性的值是什么。在这种情况下,Baz记录中Bar的值是什么。

2 个答案:

答案 0 :(得分:1)

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) }

或者,如果您无法使用范围,则可以在渲染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

答案 1 :(得分:0)

我找到了类似的东西,这就是我做的事情

<强> _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