Wasswa Samuel
Wasswa Samuel

Reputation: 2179

How to create and save an model that has a has_many/ belong_to association

I am building an application and i have a models like this

class Region < ActiveRecord::Base
  attr_accessible :region_name
  has_many :districts, dependent: :destroy
end

class District < ActiveRecord::Base
  attr_accessible :district_name
  belongs_to :region
  has_many :counties, dependent: :destroy
  validates :region_id, presence: true
 end

I have been adding districts and regions using db/seed like so

region1 = Region.find_or_create_by_region_name :region_name => 'Central'
district1 = region1.districts.create(district_name: 'Kampala')

Now this cumbersome as you can imagine so i want to create a simple form where i can add a district and associate it with the right region using a select menu.

So this my districts\new.html.erb view

<div class="region">
<%= form_for (@district) do |f| %>
<%= f.label :region %>
<%= f.collection_select :region, Region.all,:id, :region_name, :prompt => "-- Select       Region --" %>
<%= f.label :district %>
<%= f.text_field :district_name %>
<%= f.submit "Add District", class: "btn btn-large btn-primary" %>
<%end%>
</div>

This is my districts controller create method

def create
  @region = Region.find_by_region_name(params[:region_name])
  @district = @region.districts.create!(params[:district])
  if @district.save
    redirect_to :districts_path, :notice => "District added"
    else
      render :new
    end
end

This as you expect does not work. Am new to rails so am not sure how to do it correctly. How can i implement it?

Upvotes: 0

Views: 60

Answers (1)

zeantsoi
zeantsoi

Reputation: 26193

Your collection_select parameters are mis-named, and your model lookup in your controller is keyed to the incorrect parameter. See the Rails documentation here.

Something like this would work:

# app/views/districts/new.html.erb    
<%= collection_select :region, :region_id, Region.all, :id, :region_name, :prompt => "-- Select       Region --" %> # notice that `collection_select` is not being passed to `f`

# app/controllers/districts_controller.rb
def create
    @region = Region.find(params[:district][:region_id])
    ...
end

Upvotes: 1

Related Questions