user1720381
user1720381

Reputation:

Rails: collection_select in edit form

I having real problems trying to get my edit and update actions working for my app. I am wanting to edit the technologies that are linked with a project.

def edit
  @project = Project.find(params[:id])

  @project_technol = @project.projecttechnols.build
end



def update
   @project = Project.find(params[:id])
   @project.client = params[:new_client] unless params[:new_client].blank?
   @project.role = params[:new_role] unless params[:new_role].blank?
   @project.industry = params[:new_industry] unless params[:new_industry].blank?
   @project.business_div = params[:new_business_div] unless params[:new_business_div].blank?

   params[:technols][:id].each do |tech|

     if !tech.empty?

      @project_technol = @project.projecttechnols.build(:technol_id => tech) 

   end

Project model:

class Project < ActiveRecord::Base
  attr_accessible  :fullname, :edited_first_name, :edited_last_name, :first_name, :last_name, :business_div, :client, :customer_benefits, :edited_date, :end_date, :entry_date,:industry, :keywords, :lessons_learned, :project_name, :project_owner, :role, :start_date, :status, :summary, :tech , :technols, 

has_many :projecttechnols
has_many :technols, :through => :projecttechnols

accepts_nested_attributes_for(:technols)

When I enter the edit form, the previous technologies that were selected are not selected in the collection select.

EDIT form:

<%= f.fields_for(@project_technol) do |t| %>
  <%= t.label "Choose Technologies"%> </br>
  <%= t.collection_select(:id, Technol.all, :id, :tech, {}, {:multiple => true } ) %>
<% end %>

<% @project.technols.each do |t| %>
    <li><%= t.tech %> <%= link_to "Details", technol_path(t), method: :delete, %></li>
  <% end %>

I can see which technologies are there using the @project.technols.each do |t| loop, so they are being found, but they are not showing up the collection_select. Please can someone point me in the right direction. I am new to rails so it could be something every simple that I'm not understand. Thanks in advance.

Upvotes: 1

Views: 1030

Answers (1)

Pro777
Pro777

Reputation: 1704

Try something like this:

<p><%= f.label :skills %><ul>
<% for skill in Skill.all %>
    <li>
      <%= check_box_tag "user[skill_ids][]", skill.id, @user.skills.include?(skill) %>
      <%= skill.name %>
    </li>
<% end %>
</ul>
</p>

Remove the code from your update action

   params[:technols][:id].each do |tech|

     if !tech.empty?

      @project_technol = @project.projecttechnols.build(:technol_id => tech) 

   end

In your project model, you'll need something like

enter code hereattr_accessible :technols_ids

Upvotes: 1

Related Questions