Question

In a rails project I have two entities, Users and Institutions, they have a many-to-many relationship.

The views for them are set up to create new users and institutions but I want to have another view for linking the two.
In rails console all I have to do is

myuser.institutions << the_institution_i_just_created

The controller can do some of the work but how do I handle the submissions and the forms? I want to use a selection box so that the input is limited to the Institutions already in existence.

<select id="institution_selection" name="institution_sel">
<% selections = []
   Institution.all.each do |institution|
      pair = [institution.name, institution.id]
      selections.concat([pair])
   end 
   %>
   <%= options_for_select(selections) %>
</select>

So the question in summary is how do I map this submission to an object so that in the controller I can do add it to the relation?

The solution was:

Alright, so this is the solution I came up with, I'm sure there is a better way to go about it and I'll continue to look into it but at least I got something close to what I was aiming for

def test
  if !session[:user]
     redirect_to users_path, notice: "Please login first"
  end
  if params[:institution]
     @user = User.find(session[:user])
     @institution = Institution.find(params[:institution][:id])
     @user.institutions << @institution
     redirect_to @user, notice: "Institution was successfully added "
  end
end

and for the view

<%= form_tag("/users/test", :method => "post") do %>
<%= collection_select :institution, :id, Institution.all, :id, :name %>
<%= submit_tag("Search") %>
<% end %>
Was it helpful?

Solution

Use collection_select

<% from for @instancevar do |form| %>
     <%= form.collection_select :institution_id, Institution.all, :id, :name %> 
     # Do other stuff....
<% end %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top