0

Having problems creating radio buttons in a form using has_one

Model

Class User
has_one :role
accepts_nested_attributes_for :role

Class Role
attr_accessible :name
belongs_to :user

Controller

@user = build_role

Form for radio buttons

<div class="field">
 <% Role.offset(1).all.each do |role_fields| %>
  <%= radio_button_tag "user[role_fields_id][]", role_fields.id, @user.role_id == role_fields.id %>
  <%= role_fields.name %>
 <% end %>
</div>

Getting the error

undefined method `role_id' for #<User id: nil, name: nil, created_at: nil, updated_at: nil>

I'm sure I set up the relationship in the controller, why is this not working?

  • Does your `User` model have a `role_id` column? – Zajn Jan 07 '13 at 22:14
  • Why would my User model need the role_id column? @Zajn – jmorrissette Jan 07 '13 at 23:32
  • I was under the assumption that you were storing a `role_id` for each User, but what Geoff said in his answer makes sense. Seeing `@user.role_id` made me think you were trying to access a `role_id` attribute on that User instance, since according to your error, there's no `role_id` method for User instances. – Zajn Jan 08 '13 at 01:21
  • @Zajn, I should have included it in my answer, but there was a section in the documentation about `has_one` vs. `belongs_to` that made it clear that there would be no `role_id` in this direction. (I had to look it up to confirm it to myself before answering.) – Geoff Jan 08 '13 at 01:49
  • @Geoff, Right, I just wasn't sure if by chance he had mixed up his associations and used `has_one` where he meant `belongs_to`. I know I get them mixed up all the time. – Zajn Jan 08 '13 at 02:10

1 Answers1

0

I think this line:

<%= radio_button_tag "user[role_fields_id][]", role_fields.id, @user.role_id == role_fields.id %>

Should be corrected to this:

<%= radio_button_tag "user[role_fields_id][]", role_fields.id, @user.role.id == role_fields.id %>

I hope that helps.

Geoff
  • 2,208
  • 1
  • 16
  • 17