0
votes

I created a user and program table, and a joined table. Each user has_and_belongs_to_many :programs and each program has_and_belongs_to_many :user.

Using dropdown select, I wanted to select a program and save it to the user. But after I save, the display always shows the text "Program" instead of the actual program name that was selected from the dropdown.

Dropdown select form:

<%= f.collection_select(:program_ids, Program.all, :id, :name, :include_blank => "Choose a Program" ) %>

Display programs that the user belongs to:

<% @user.programs.each do |program| %>
  <%= program.name %> 
<% end %>

I'm not sure if I am saving the program to user correctly or if I am displaying the variable wrong. I followed the idea from how to have a dropdown select field in a rails form.

Any suggestion will help, Thanks!

1
can u try this one: <%= f.select :program_id, Program.all.map {|c| [c.name, c.id] }, {prompt:"Choose a Program"} %> - 7urkm3n
@7urkm3n I tried the code you posted and I get the same result. It just lists as "Program" instead of the actual program name such as "Math". - teresa
how exactly do u want to save ids, many or just one id of program ? cuz yr db relationship many to many. and if im not wrong it requires to save it array, not a just integer. - 7urkm3n

1 Answers

0
votes

I was able to find a solution to my problem. The dropdown select form and view code stayed the same. It now displays the program associated with the user instead of showing the text "Program".

Added serialize to program.rb:

class Program < ActiveRecord::Base
  has_and_belongs_to_many :users
  serialize :program
end