0
votes

I'm my project I have two tables, Jobs and Counties. Each job record can be associated with many counties. So first, this is a many to many relationship correct?

I'd like to have a fieldset of checkboxes in my jobs form that if a checkbox is checked a relationship between the job_id and the checked county_id is made.

So I'm thinking I need a join table with only job_id and county_id, correct?

Here's what I have so far. So far it'll save a job record, but not the job/county associations.

"counties_jobs_join" migration

class CreateCountiesJobsJoin < ActiveRecord::Migration
  def change
    create_table :counties_jobs, :id => false do |t|
      t.integer :county_id
      t.integer :job_id
    end
  end
end

"counties" model

class County < ActiveRecord::Base
  has_and_belongs_to_many :jobs
end

"jobs" model

class Job < ActiveRecord::Base
  has_and_belongs_to_many :counties
end

As for my form, I'm using simple_form, so here's what I have for the checkboxes.

<%= simple_form_for(@job) do |f| %>
  <fieldset>
    <legend>Counties</legend>
    <%= f.association :counties, :as => :check_boxes, :collection => County.all.sort, :selected => @job.counties, :label => false %>
  </fieldset>
  <%= f.button :submit %>
<% end %>

I've checked in the database, but it's not creating any records in counties_jobs. Any help is greatly appreciated!

1
need params from log that submitted to create action - Nitin Jain
if you ask any question than please provide any detail asked so it will be easier to provide solutions. keep responsive towards your question :) - Nitin Jain
accepts_nested_attributes_for :counties put this in model Job - Nitin Jain

1 Answers

0
votes

I cannot say what is going wrong with you creation but I think it is not a problem of your habtm relationship. In fact, if you can see the counties checkboxes, I can assure you your relationship is working.

Probably what it is not happening is that either you are not allowing :accept_nested_attributes or not doing it manually in your create controller.