开发者

Using multiple dropdowns instead of a text field in Rails 3

I'm currently building my first Rails 3 app, but can't quite figure out how to get one piece of functionality.

I have a temperature field, but rather than using <%= f.text_field :temp %>, I'd like to have two dropdowns. The first dropdown would allow choosing 97-99, while the second dropdown would allow choosing 0-9. After the user has made t开发者_JS百科heir selection and saved, the results should be concatenated into e.g. 98.2

What is the best way to achieve this in Rails 3? Thanks!


I suggest creating two virtual attributes, one for each part of the temperature (97-99 and 0-9). Then define a before_validation method on the model that takes those two values (that aren't persisted to the database) and sets the temp attribute accordingly (that is persisted to the database). This way you can validate the temp value as you normally would and query it as you would any other regular value in the database. It also keeps your view code easy on the eyes. There are other ways to accomplish this though.

Ryan Bates has a great screencast on virtual attributes. http://railscasts.com/episodes/167-more-on-virtual-attributes


You could make two attributes in whatever model you use. One for each field you want to use. Then when you hit save you have code in the model and uses these attributes to form the temperature attribute.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜