开发者

Rails - Should an object's types be in its own model?

I have a contact, and contact has_many :phones. The phones table has a column named, phones_desc, where I want to include the type of phone number the user has saved.

My question / Best practice

Should I provide a select with manually provided options (such as "mobile", "work", "home")...

-or-

...create a new model named phones_types where I can add the values I'd like, thus creating a unique ID for each one. Then I can do the following after changing phone_desc to phone_type_id, adding phones has_many :phone_types and giving the phone_types table a name column:

@phone = Phone.first
@phone.type.name

Sidenote

I'm currently doing it with the first option (not a separate model) and am having trouble with it selecting the value when I go to edit the parent object. In other words, the select options don't have the saved value selected when going to edit phone numbers.

It always has the first option selected, so the user may inadvertently change the phone_desc without realizing it.

If the first option is in fact the better way to go, would you have any insight on how to get the objects value to be the selected value when editing p开发者_如何转开发hones descriptions via a select?


I'd still go for a separate model for the phone type. This way, you can more easily add other phone types later on. Also think about i18n, it might save you some headache when translating "Mobile" to Japanese.


Turns out that option one works just fine, and I can get the selected option to work too. It was a problem in the order that I supposed the option parameters.

I changed:

<%= f.select :number_desc, '<option value="mobile">Mobile</option><option value="work">Work</option><option value="home">Home</option><option value="other">Other</option' %>

to:

<%= f.select :number_desc, [["Mobile", "mobile"], ["Work", "work"], ["Home", "home"], ["Other", "other"]] %>

And voila - selected works fine. :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜