Search code examples
ruby-on-railsruby-on-rails-4collection-selectgrouped-collection-select

Collection Select undefined method in Rails 4


I have a form that requires pulling all of the objects in the database into a select field. I've reviewed other SO questions about collection_select and can't seem to figure out why I'm getting an undefined method error.

# Loan Application Model
class LoanApplication < ActiveRecord::Base
  has_many :loan_securities, :dependent => :destroy
  accepts_nested_attributes_for :loan_securities, :allow_destroy => true
end

# Loan Security Model
class LoanSecurity < ActiveRecord::Base
  has_one :security_type
  accepts_nested_attributes_for :security_type
end

# Security Type Model
class SecurityType < ActiveRecord::Base
  belongs_to :loan_security
end

Every loan application will have_many loan securities and each loan security will have one security type. I've seeded the DB with some security types already. So far the form is working fine with the loan application to loan security relationship.

<%= nested_form_for [@business, @loanapplication], method: :put, :class => "form-horizontal", url: wizard_path, :html => { :multipart => true } do |f| %>
    <%= f.fields_for :loan_securities, :wrapper => true do |loan_security| %>
        <%= loan_security.collection_select(:security_type_id, SecurityType.all, :id, :name) %>
    <% end %>
<% end %>

In the loanapplications_controller I've added the params for loan security and security type

loan_securities_attributes: [:id, :_destroy, security_type_attributes: [:security_type_id, :name]]

The error itself:

undefined method `security_type_id' for #<LoanSecurity:xxxxxxx>

Solution

  • Do this:

    <%= loan_security.collection_select( :security_type_id, ::SecurityType.all, :id, :name) %>