Mike Wiesenhart Mike Wiesenhart - 1 month ago 7
Ruby Question

ID's are not saving to DB across models/controllers in Rails 4

I have a Landlord model, a LandlordCompany model, and a LandlordAddress model. I need to save the landlord_id to the landlord_comapnies table, and the landlord_company_id to the landlord_address table. I have hidden_fields to try to accomplish this which I have done in the past, but it is not working in this instance. What am I missing? Any help welcomed. Thanks in advance!

landlord.rb

class Landlord < ActiveRecord::Base
has_many :landlord_companies
end


landlord_company.rb

class LandlordCompany < ActiveRecord::Base
belongs_to :landlord
end


landlord_address.rb

class LandlordAddress < ActiveRecord::Base
belongs_to :landlord_company
end


_form.html.erb <- landlord_companies

<div class="field">
<%= f.hidden_field :landlord_id, :value => params[:landlord_id] %>
</div>


_form.html.erb <- landlord_addresses

<div class="field">
<%= f.hidden_field :landlord_company_id, :value => params[:landlord_company_id] %>
</div>


Routes.rb

resources :landlords do
member do
resources :landlord_companies do
member do
resources :landlord_addresses
end
end
end
end


Landlords Controller

private
# Use callbacks to share common setup or constraints between actions.
def set_landlord
@landlord = Landlord.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def landlord_params
params.require(:landlord).permit(:name, :rating, :contact_name, :contact_number, :listing_agent_id, :own_application, :own_credit, :accepts_roommate_matchups, :management_company)
end


Landlord_companies Controller

private
# Use callbacks to share common setup or constraints between actions.
def set_landlord_company
@landlord_company = LandlordCompany.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def landlord_company_params
params.require(:landlord_company).permit(:llc_name, :landlord_id)
end


Landlord_addresses controller

private
# Use callbacks to share common setup or constraints between actions.
def set_landlord_address
@landlord_address = LandlordAddress.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def landlord_address_params
params.require(:landlord_address).permit(:address_line_one, :address_line_two, :city, :state, :zip, :super_name, :super_number, :landlord_company_id, :latitude, :longitude)
end

Answer

You need to add that landlord companies has_many landlord addresses. Then when you create a new object you need to follow the docs and do something like landlord.landlord_companies.new(lord_params)