Loenvpy
Loenvpy

Reputation: 919

Association Companies industries in rails

I have created a many to many relationship between company and industry so when I create a company I can chose from a select collection of one or many industries for the company. Once the company is created and redirects to the company page I don’t get the industry info for the company. Can somebody help me understand why?

this is my company model

class Company < ActiveRecord::Base
    has_many :industres
    has_many :industies, through: :industrializations
end

this is my industry model

class Industry < ActiveRecord::Base
    has_many :industrializations
    has_many :companies, through: :industrializations
end

this is my industrialization model

class Industrialization < ActiveRecord::Base
    belongs_to :company
    belongs_to :industry
end

this is my _form.html.erb

<%= f.label :industry %><br />
<%= f.collection_select :industry_ids, Industry.all, :id, :name, :prompt => "Choisir votre secteur d'activité"  %>

and this is my company show.html.erb

<p>
  <strong>Name:</strong>
  <%= @company.name %>
</p>

<p>
  <strong>Description:</strong>
  <%= @company.description %>
</p>

<p>
  <strong>Country:</strong>
  <%= @company.country %>
</p>

<p>
  <strong>City:</strong>
  <%= @company.city %>
</p>

<b>Sector:</b>
<ul>
  <% @company.industries.each do |industry| %>
    <li><%= industry.name %></li>
  <% end %>
</ul>

this is my schema

create_table "companies", force: true do |t|
    t.string   "name"
    t.text     "description"
    t.string   "country"
    t.string   "city"
    t.datetime "created_at"
    t.datetime "updated_at"
end

create_table "industrializations", force: true do |t|
    t.integer  "company_id"
    t.integer  "industry_id"
    t.datetime "created_at"
    t.datetime "updated_at"
end

create_table "industrie", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
end

the industry names are in the seed file

the company model was created via scaffold

Upvotes: 0

Views: 86

Answers (1)

Pavling
Pavling

Reputation: 3963

You've tagged this as both Rails 3.2 and Rails 4, but they each have different ways of accepting form information through the controller to the models.

In Rails 3.2 you would have to ensure that the industry_ids attribute was marked as attr_accessible. But since you're not complaining of a 'mass assignment' error, I think you are probably on Rails 4.

In Rails 4 you now need to use the 'strong parameters' to allow params through to the model - you might find that the scaffolded controller is already doing this for the company's other attributes, and you just need to add industry_ids to permit them.

See How is attr_accessible used in Rails 4? for some more info.

Upvotes: 1

Related Questions