user984621
user984621

Reputation: 48443

Rails - disable option in select (based on the condition)

I have select:

= f.select(:category_id, @categories, :html_options => {:class => 'select_box'}, {:disabled => true if category.id == 18})

The piece of code above obviously returns an error, but how to disable an option according by id?

Upvotes: 3

Views: 6983

Answers (4)

aldrien.h
aldrien.h

Reputation: 3615

For select_tag, we can do:

<%= select_tag "sample", options_for_select(
    [['A', 'a'], ['B', 'b'], ['C', 'c']]),
    {class: 'form-control', disabled: data.present? == false ? true : false}
%>

Upvotes: 0

dax
dax

Reputation: 10997

Ran into this recently and used the following solution:

#view
= f.select(:category_id, @filtered_categories, :html_options => {:class => 'select_box'}

#controller
@filtered_categories = Category.all.select do |category|
  [logic here]
end

Upvotes: 0

Zernel
Zernel

Reputation: 1547

<%= f.select :status, STATUSES.map{|s| [s.titleize, s]}, { disabled: DISABLED_STATUSES.map{|s| [s.titleize, s]} %>

Upvotes: 1

Purple Hexagon
Purple Hexagon

Reputation: 3578

Haven't tested this but in your controller could you not do

@checkvar = @category.id == 18 ? true : false

then in the view

f.select(:category_id, @categories, :html_options => {:class => 'select_box'}, {:disabled => @checkvar})

or in the model write a function to test

def disable_select 
    if self.id == 18
        true
    else 
       false
    end
end

then in the view

f.select(:category_id, @categories, :html_options => {:class => 'select_box'}, {:disabled => @category.disable_select})

Upvotes: 5

Related Questions