Not saving unique id in different table - Rails 4

Question!

I have a landlord and a landlord_company model. I am trying to pass the landlord_id into the landlord_company table once a new landlord_company is created. I have a f.hidden_field in the landlord_company form, but it is not working.

landlord mode:

has_many :landlord_companies

landlord_company model:

belongs_to :landlord

landlord_company controller:

def new
   @landlord_company = LandlordCompany.new
end

def create
   @landlord_company = LandlordCompany.new(landlord_company_params)
   @landlord = Landlord.find(params[:landlord_id])

   respond_to do |format|
      if @landlord_company.save
         format.html { redirect_to @landlord_company, notice: 'Landlord company was successfully created.' }
         format.json { render :show, status: :created, location: @landlord_company }
      else
         format.html { render :new }
         format.json { render json: @landlord_company.errors, status: :unprocessable_entity }
      end
    end
  end

landlord_company form:

<div class="feedback-container">
   <%= form_for @landlord_company, url: {action: "create"}, html: {class:  "new.html.erb"} do |f| %>
      <% if @landlord_company.errors.any? %>
         <div id="error_explanation">
            <h2><%= pluralize(@landlord_company.errors.count, "error") %> prohibited this landlord_company from being saved:</h2>

            <ul>
            <% @landlord_company.errors.full_messages.each do |message| %>
               <li><%= message %></li>
            <% end %>
            </ul>
          </div>
       <% end %>

       <div class="field">
          <%= f.label :llc_name, class: "general-text-label" %><br>
          <%= f.text_field :llc_name, class: "general-text-field" %>
       </div>
       <div class="field">
          <%= f.hidden_field :landlord_id, :value => params[:landlord_id] %>
       </div><br>
       <div class="actions">
          <%= f.submit "Submit", class: "btn btn-black btn-4x" %>
       </div>
     <% end %>
   </div>

Routes.rb:

resources :landlords do
   member do
      resources :landlord_companies
   end
end


Answers

I figured out what was wrong after almost a days worth of work. I nested my resources wrong. I had them as...

resources :landlords do
   member do
      resources :landlord_companies
   end
end

...and is was messing everything up! Rookie mistake.



Change your create action to as follows:

def create
   @landlord_company = Landlord.landlord_companies.new(landlord_company_params)

Then make sure to add the landlord_id to the whitelisted params in your "landlord_company_params" method and it will automagically handle the association for you.

By : bkunzi01


This video can help you solving your question :)
By: admin