4

newbie here, first post.

I just spent like 4 hours trying to assign one category to a post (trying out a regular blog thing) via radio buttons, to no avail. The association is working fine, and ultimately I managed to get it working with a select menu, but for some reason it seems radio buttons are simply not meant for that.

I really don't like using a select menu for that because I only have 4 categories and having to click twice to select a single one is 1 click too many. So I would really like to use radio buttons instead.

I checked out the other question on the subject and searched the web senseless but it only helped me get a more diverse array of errors: Undefined methods, AssociationTypeMismatch, category_ids of 0, you name it. So I gave up for today and decided to create a account and see if anyone can crack this one. Any help will be appreciated.

Thanks.

Community
  • 1
  • 1
San Diago
  • 1,030
  • 1
  • 12
  • 26
  • I didn't even had it anymore. I tried every possible combination I could figure out from the form helper API and nothing worked, so I got rid of it altogether. Turns out that was exactly the problem; the solution looks nothing like it says there. – San Diago Mar 23 '09 at 19:36

1 Answers1

3

Here we go. In RailsCasts Episode 17 Ryan uses habtm and checkboxes to do this kind of thing. I modified it to use belongs_to and radio buttons. 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

Post Create View (removed the default textbox 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>
Ilya Cherevkov
  • 1,743
  • 2
  • 17
  • 47
Restore the Data Dumps
  • 38,967
  • 12
  • 96
  • 122
  • Now I'm embarrassed, but grateful! I actually tried it like that, but somehow made it go wrong. But mostly I got too caught up trying to get things to work by following the radio_button syntax in the form helper API, which looks NOTHING like that, but I assumed was the official way to go. Thanks! – San Diago Mar 23 '09 at 19:34
  • Oh, just one thing: The last bit is not `category.category_name`, but actually `category.name`. Just thought I'd leave it here to posterity. – San Diago Mar 23 '09 at 19:38
  • @Baby Diego: You can see in my script/generate that my category model has the property category_name. you may have just created name as the property in your model...this is exactly the code I tested when I was writing it... – Restore the Data Dumps Mar 23 '09 at 20:05
  • Hello, when using "for category in Categories.find(:all)" how would you ensure one of the radio buttons is selected 'true' by default??? – trying_hal9000 Dec 30 '14 at 10:07