Rails 模型有 2 个外键,但在提交时只保存了一个 form_for

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

我正在尝试使用嵌套资源保存 form_for,该嵌套资源将数据输入到属于其他 2 个模型并具有 2 个外键的模型中:User_id 和 listing_id。

问题是只有 user_id 被保存,尽管两个 ID 都被创建了,如控制台所示,并且 listing_id 被传递了正确的值。

我可能遗漏了一些明显的东西,但我对 Rails 还很陌生。非常感谢您的帮助。谢谢。

应用模型:

    belongs_to :user
    belongs_to :listing

上市型号:

    has_many :applications

用户模型

    has_many :applications

控制器:

    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

查看:

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

routes.rb

    resources :listings do
      resources :applications
    end

这是我在控制器中得到的- http://i.stack.imgur.com/e52T0.png。 listing_id 已作为参数传递,但在保存表单时丢失了。

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]]

似乎 listing_id 被传递但没有被插入。这是为什么?

您的 'new' 操作不应创建任何内容。应该是:

@application = Application.new

并且您的 "update" 操作不应该是创建新记录,而是更新刚刚编辑的记录。这样就变成了:

@application = Application.find(params[:id])
@application.update_attributes(application_params)

一个可能的解决方案是在视图中添加一个隐藏字段,该字段将预先填充 listing_id。

如果将其添加到视图中,它会起作用:

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