How to assign one category to a message using radio buttons in Rails?

newbie here, first post.

I just spent 4 hours trying to assign one category to a post (try out an ordinary thing on a blog) using a radio button, but to no avail. The association works fine, and in the end I managed to get it to work with the selected menu, but for some reason it seems that the radio buttons are simply not designed for this.

I really don’t like using the selection menu for this, because I have only 4 categories, and you need to double-click to select one of them, there is too much one click. So I really would like to use radio buttons.

I checked another question on the topic and searched the Internet pointlessly, but it only helped me get a more diverse array of errors: Undefined methods, AssociationTypeMismatch, category_ids 0, you name it. So I gave up today and decided to create an account and see if anyone could hack it. Any help would be appreciated.

Thanks.

+4
source share
1 answer

Here we go. In RailsCasts Episode 17, Ryan uses habtm and flags to do such things. I changed it to use belongs_to and switches. Thanks for the exercise.

> script/generate scaffold category category_name:string > script/generate scaffold post post_name:string, post_content:text, category_id:integer 

Post model

 Class Post < ActiveRecord::Base belongs_to :category End 

Create Create View (remove the default text box for category_id)

 ... <p> <% for category in Categories.find(:all) %> <div> <%= radio_button_tag "post[category_id]", category.id, @post.category_id == category.id %><%= category.name %> </div> <% end %> </p> 
+3
source

All Articles