Xiv
Xiv

Reputation: 10043

Selecting belongs_to parents in a form?

Imagine I have something like this:

class Employer < ActiveRecord::Base
  has_many :employees
end

class Employee < ActiveRecord::Base
  belongs_to :employer
end

And I want to create a new Employee, and give a form with with a drop down box, where I can select which Employer I wish to associate it with. The dropdown should list every employer in the system. How can I do this?

Thanks.

Upvotes: 0

Views: 101

Answers (1)

Benjamin M
Benjamin M

Reputation: 24527

I think you haven't understood what this association does. Or I haven't understood what you really want.

If you want to display ALL employers in a view, you simply have to fetch them in the corresponding controller action and save it in an instance variable. Then you can access its contents inside the view.

controller action:

@employers = Employer.all
...

corresponding view:

<%= collection_select @employers %>

Upvotes: 1

Related Questions