Rails - Postgresql中的数据库条目不正确

时间:2015-09-02 21:13:26

标签: ruby-on-rails postgresql

我正在尝试创建一个表单来处理地址的创建。我有三个模型,AddressInfo,Address和Client。 AddressInfo将存储地址类型,如礼物,邮寄或雇主,并链接到ClientID和AddressID。这用于防止重复地址,以防有人使用其雇主地址作为邮寄地址。我目前遇到的问题是我似乎无法将AddressID链接到AddressInfo行。

这是我的rails控制台尝试和所需的行为:enter image description here

这是我的输出:此时忽略地址中的条目,因为这些只是种子文件。 Addressinfo(3)是我试图通过接口添加的条目,它不会创建新地址。 enter image description here 以下是我的观点:

<%= form_for(@client) do |f| %>
    <%= f.fields_for :address_infos do |presinfo_form|%>
        <%= presinfo_form.fields_for :addresses do |address_form| %>
             <%= address_form.label :"Present Address" %>
             <%= address_form.text_field :street %>
        end
        <%= presinfo_form.label :"Type" %>
        <%= presinfo_form.text_field :addresstype, :value => "present" %>
    end
end

模特:

class AddressInfo < ActiveRecord::Base
    belongs_to :client
    belongs_to :address
    accepts_nested_attributes_for :address
end

class Address < ActiveRecord::Base
    has_many :address_infos
    has_many :clients, through: :address_infos
end

class Client < ActiveRecord::Base
    has_many :address_infos
    has_many :addresses, through :address_infos
accepts_nested_attributes_for :addresses, :address_infos, reject_if: :all_blank, allow_destroy: true
end

客户控制器:

class ClientsController < ApplicationController
def new
    @client = Client.new
    @client.address_infos.build
    @client.addresses.build
end

def create
    @client = Client.new(client_params)
    if @client.save
        redirect_to root_url 
    else
        render 'new'
    end
end


private
    def client_params
        params.require(:client).permit(:firstname, :middlename, :lastname, 
        address_infos_attributes: [:ownorrent, :addresstype, :yearsofresidency,
        addresses_attributes: [:street, :city, :state, :zipcode]]
    )
    end
end

0 个答案:

没有答案