本文介绍了尝试在Rails中保存嵌套属性时出现ActiveRecord :: AssociationTypeMismatch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通读了许多有关"has_one关系和嵌套属性"的页面,但未能成功完成这项工作.任何帮助都很棒.

I read through a lot of pages on `has_one relationships and nested attributes but haven't been successful in making this work. Any help would be fantastic.

每个用户的has_one网络.我正在尝试以一种形式收集两个属性的信息,但一直在获取异常ActiveRecord::AssociationTypeMismatch in UsersController#create

Each User has_one Network. I'm trying to gather information for both attributes in one form but keep getting the exception ActiveRecord::AssociationTypeMismatch in UsersController#create

传递的参数是:

{"utf8"=>"âœ"",
 "authenticity_token"=>"I54tm1ovzHEHaXbBLTT+5tqBJv2795sKg978ot3HDBc=",
 "user"=>{"name"=>"Bilbo Baggins",
 "email"=>"[email protected]",
 "password"=>"[FILTERED]",
 "password_confirmation"=>"[FILTERED]",
 "network"=>{"home_lng"=>"-87.91894912719727",
 "home_lat"=>"43.03812464542969",
 "center_lng"=>"-87.91894912719727",
 "center_lat"=>"43.03812464542969",
 "radius"=>"500"}},
 "commit"=>"Sign up"}

我猜想Network的参数必须以某种方式显示为network_attributes,但是我不确定如何.

I'm guessing the parameters for Network have to somehow show up as network_attributes but I'm not sure how.

控制器:

def create
    @user = User.new(params[:user])
    if (@user.save)
      sign_in @user
      flash[:success] = "One ring to rule them all!"
      redirect_to @user
    else
      @title = "The journey begins..."
      render 'new'
    end
end

查看:

<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %><br />
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Confirmation" %>
<%= f.password_field :password_confirmation %>
  <%= f.fields_for @network do |fn| %>
    <%= fn.hidden_field :home_lng %>
    <%= fn.hidden_field :home_lat %>
    <%= fn.hidden_field :center_lng %>
    <%= fn.hidden_field :center_lat %>
    <%= fn.hidden_field :radius %>
  <% end %>

当然还有模型:

class User < ActiveRecord::Base
  attr_accessor :password
  attr_accessible :name, :email, :password, :password_confirmation, :network_attributes, :network
  has_one  :network, :foreign_key => "user_id",
                     :dependent => :destroy

  accepts_nested_attributes_for :network,
                            :reject_if => :all_blank,
                            :allow_destroy => true
end

class Network < ActiveRecord::Base
  attr_accessible :home_lng, :home_lat, :center_lng, :center_lat, :radius
  belongs_to :user
end

谢谢

推荐答案

如果其他人遇到相同的问题,我可以通过以下方法解决:

Incase someone else is having the same issue, I resolved this by changing:

<%= f.fields_for @network do |fn| %><%= f.fields_for :network do |fn| %>,并从用户模型中删除:network作为可访问属性.

<%= f.fields_for @network do |fn| %> to <%= f.fields_for :network do |fn| %> and removing :network as an accessible attribute from the user model.

这篇关于尝试在Rails中保存嵌套属性时出现ActiveRecord :: AssociationTypeMismatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 02:22