ruby-on-railsrubyruby-on-rails-4foreign-key-relationshipnested-form-for

Rails model with 2 foreign keys but only one gets saved when submitting form_for


I'm trying to save a form_for with nested resources that inputs data into a model that belongs to 2 other models and has 2 foreign keys: User_id and listing_id.

The problem is that only the user_id gets saved despite the fact that both ids are being created ,as shown in the console, and the listing_id is passed with the correct value.

I might be missing something obvious but i'm fairly new to Rails. Help is much appreciated. Thanks.

Application model:

    belongs_to :user
    belongs_to :listing

Listing model:

    has_many :applications

User model

    has_many :applications

Controller:

    class ApplicationsController < ApplicationController
    before_action :authenticate_user! 


    def index

    end

    def update
      @application = current_user.applications.create  
    end


    def new 
      @application = Application.new
      @listing = Listing.find(params[:listing_id])

    end

    def create
      @application =     current_user.applications.create(application_params)
      redirect_to listing_applications_path
    end

    def your_applications
      @apps = current_user.applications

    end

    private
      def application_params
        params.require(:application).permit(:listing_id, :st_address, :unit, :city, :state, :move_in,:first_name, :last_name, :phone_numer, :pets, :current_address, :previous_landlord_name, :previous_landlord_phone, :company, :company_address, :company_phone, :is_40X, :annual_income)
      end
  end

View:

      <%= form_for [:listing, @application] do |f| %>

routes.rb

    resources :listings do
      resources :applications
    end

This is what I get in the controller- https://i.sstatic.net/e52T0.png. The listing_id is passed already as a parameter but gets lost when saving the form.

Processing by ApplicationsController#new as HTML Parameters: {"listing_id"=>"13"}

Processing by ApplicationsController#create as HTML Parameters: {........, "listing_id"=>"13"}

User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 11]] (0.1ms) begin transaction SQL (0.4ms) INSERT INTO "applications" (.......) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) [....., ["user_id", 11], ["created_at", ....], ["updated_at", ....]]

Listing Load (0.1ms) SELECT "listings".* FROM "listings" WHERE "listings"."id" = ? LIMIT 1 [["id", 13]]

It seems like the listing_id is being passed but not inserted. Why is that?


Solution

  • A possible solution is to add a hidden field in the view that will be pre populated with the listing_id.

    It works if this is added to to the view:

        <%= f.text_field :listing_id, value: params[:listing_id], class: "form-control hidden"%>.