Question

I have two boolean fields in my model. There is a dependency that only one can be true at a time. On my view page I want to display them as a radio inputs using formtastic. And not separately but as a single radio group. I know there is a rails way but somehow I am not able to find it.

Please help. Thanks in Advance.

Was it helpful?

Solution

You could create a virtual attribute to get and set the appropriate value. For example, if you had a boolean named male and a boolean named female, you could control both with the gender attribute like this:

class User
  def gender= gender
    self.male = (gender == 'M')
    self.female = (gender == 'F')
  end

  def gender
    male ? 'M' : 'F'
  end
end

You could then have a radio button group for selecting gender:

radio_button_tag :gender, 'M'
radio_button_tag :gender, 'F'

Of course you always have the option of combining the values into a single 3-state attribute, like gender which can be 'M', 'F' or NULL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top