开发者

Two Boolean fields. Single input field. Ruby on Rails

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 f开发者_运维问答ormtastic. 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜