简体   繁体   中英

Dropdown Box Ruby on Rails question

I am new to rails so go easy. I have two tables that I am trying to work with here, 'post' and 'category'.

The 'post' table includes the following columns, title:string content:text category:string. The 'category' table simply contains name:string.

The idea is that the client can manage the categories and also when adding a new post, they can select from a drop down that references their categories.

What is the best way to accomplish this?

You might want to model the category differently. The usual approach is to create a PostCategory model and controller, and use a relation from posts to PostCategory. Read up on belongs _to and the other rails associations before you get much further into this project. When you're ready to continue, take a look at formtastic , it makes handling the forms for the associations much easier to code

flyfishr64 is right, the "correct" way to do this would be to put the categories in their own model/table.

There's lots of helpers like collection_select that will take your list of categories ( PostCategory.all ) and make a dropdown list for you with the appropriate name to save it in a specific field.

That said, you could pull a distinct list of the entries in that column already and use that for your dropdown, but it's a lot more hassle than just making a model for the category.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM