DWB
DWB

Reputation: 1554

Form select being populated in an odd manner

I have a select form which is populated oddly. I was wondering whether I could get an explanation.

Schema:

I have a User model which has a many to many with a model called Conversations. Conversations in turn has_many Messages and Messages belongs to Conversations. User and Messages have no links other than that.

Message controller

I am debugging a small messaging system so I decided to pass in all users (I know, I know) to my view just so I could display them in a dropdown and test send messages to them. Basically just

def new    
  @message = Message.new
  @users = User.all
end

For some odd reason I have to have belongs_to :user in my Message class or I get the error undefined method "user" for #<Message:0x0000000581b898>

View

In my form I basically have

<%= form_for(@message) do |f| %>
<div class="form-group">
    <%= f.select :user, collection: @users.all.map { |user| [user.id, user.name] }%>
</div>

Other nonsense

<% end %>

Problem

So when generating a new message why is my dropdown being populated like its trying to access Message.User.id rather than just User.id if I am giving the correct data with @users= User.all ?

Thanks

Upvotes: 0

Views: 66

Answers (2)

vee
vee

Reputation: 38645

It's because you're using the form builder instance f to define select for :user. If you don't want to associate :user with message, you could use select_tag.

<%= select_tag :user, options_for_select(@users.all.map { |user| [user.id, user.name] }) %>

Upvotes: 1

SHS
SHS

Reputation: 7744

That's because your form is trying to access the user method/attribute of your message object.

f.select :user

Upvotes: 1

Related Questions