【问题标题】:Rails 4 Nested form has_many through association and databaseRails 4通过关联和数据库嵌套表单has_many
【发布时间】:2015-08-15 00:11:06
【问题描述】:

所以我有三个模型客户端,地址和地址信息。但是,当我为 address 和 address_info 创建嵌套表单时,我基本上得到了我打算给它的行数。前三行将绑定地址类型和客户端 ID,其他三行绑定客户端 ID 和地址 ID。以下是输出示例:

如您所见,行没有与行关联的地址和客户端 ID。我不知道如何解决这个问题。

这是我的模型:

#client model
has_many :address_infos
has_many :addresses, through: :address_infos
accepts_nested_attributes_for :addresses, :address_infos, reject_if: :all_blank, allow_destroy: true

#addressinfo model
belongs_to :client
belongs_to :address

#address model
has_many :address_infos
has_many :clients, through: :address_infos

这是我的客户控制器:

def new
    @client = Client.new
    @client.address_infos.build
    @client.addresses.build
end
def create
    @client = Client.new(client_params)
end
private
    def client_params
        params.require(:client).permit(:firstname, :middlename, :lastname, 
        addresses_attributes: [:street, :city, :state, :zipcode], 
        address_infos_attributes: [:ownorrent, :addresstype, :yearsofresidency])
    end
end

这是我的观点,请注意,我没有包括邮寄地址和以前的地址的嵌套表格:

 <%= form_for(@client) do |f| %>
    <%= f.fields_for :addresses do |addresses_form| %>
        <!-- misc. code -->
    <%= f.fields_for :address_infos do |addressinfo_form| %> 
        <%= addressinfo_form.label :ownorrent, "Own", :value => "Own" %>
        <%= addressinfo_form.radio_button :ownorrent, :own %>                       
        <%= addressinfo_form.label :ownorrent, "Rent", :value => "Rent" %>
        <%= addressinfo_form.radio_button :ownorrent, :rent %>
        <%= addressinfo_form.text_field :yearsofresidency, class:"form-control", id:"inputfield", placeholder:"Years" %>
        <%= addressinfo_form.text_field :addresstype,:value => "presentaddress" %>
    <% end %>
<% end %>

更新 所以在做了建议之后,我最终在我的数据库中得到了这个: 我尝试添加的地址是 123 Fake St。其他的东西是直接播种的。 address_id 仍然不支持其余的东西。我还更新了我当前的模型。

【问题讨论】:

    标签: ruby-on-rails postgresql


    【解决方案1】:

    您应该在保存到数据库之前控制嵌套属性。使用reject_ifallow_blank 选项来防止和销毁空白记录。

    accepts_nested_attributes_for :addresses, :address_infos, reject_if: :all_blank, allow_destroy: true
    

    更多参数控制选项,请访问链接http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

    谢谢

    【讨论】:

    • 感谢您的回复。这就是代码的全部错误吗?我还没有控制嵌套属性,因为我想看看我是否可以得到任何东西来推动那里。
    • 只需在您的模型中尝试上述解决方案。它将控制嵌套属性并解决您的问题。谢谢
    • 您应该使用 validates_associated 来验证 associated_records。
    猜你喜欢
    • 2014-03-25
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 1970-01-01
    • 2016-03-01
    • 2015-12-19
    相关资源
    最近更新 更多