lundi 5 août 2019

Rails does not create associated model

I created a form where a user can create a profile. In the form the user can select multiple companies. A profile has many companies through a join-table named profile_companies. My code does create a new profile, but it does not create the association. Meaning that when I hit in the console: Profile.last.companies it returns an empty array. When I check the params before a profile is created, it does show me a full array for company_ids. So it looks like it cannot pass these values and create the association. Does anyone have an idea where the error is?

Here is my Profile model:

class Profile < ApplicationRecord
  belongs_to :user
  has_many :profile_companies
  has_many :companies, through: :profile_companies

  STATUSES = ["currently looking for a job", "employed but open for a new challenge"]
  validates :status, inclusion: {in: STATUSES}
end

here is my company model:

class Company < ApplicationRecord
  has_many :vacancies
  has_many :profile_companies
  has_many :profiles, through: :profile_companies
end

here is my profiles controller:

class ProfilesController < ApplicationController
  def new
    @profile = Profile.new
  end
  def create
    @profile = Profile.new(params_profile)

    if @profile.save
      redirect_to profile_path
    else
      render :new
    end
  end

  private

  def params_profile
    params.require(:profile).permit(:status, :name, :content, :company_ids)
  end

end




Aucun commentaire:

Enregistrer un commentaire