views:

245

answers:

1

Hello, 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.

+1  A: 

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.category_name %>
   </div>
 <% end %>
</p>
Jason Punyon
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!
Baby Diego
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.
Baby Diego
@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...
Jason Punyon
Oh, of course. Perfect.
Baby Diego