【问题标题】:ActiveRecord::AssociationTypeMismatch when attempting to save nested attributes in Rails尝试在 Rails 中保存嵌套属性时的 ActiveRecord::AssociationTypeMismatch
【发布时间】:2011-02-16 00:08:56
【问题描述】:

我阅读了很多关于 `has_one 关系和嵌套属性的页面,但未能成功完成这项工作。任何帮助都会很棒。

每个用户都有一个网络。我正在尝试以一种形式收集这两个属性的信息,但不断收到异常 ActiveRecord::AssociationTypeMismatch in UsersController#create

传递的参数是:

{"utf8"=>"✓",
 "authenticity_token"=>"I54tm1ovzHEHaXbBLTT+5tqBJv2795sKg978ot3HDBc=",
 "user"=>{"name"=>"Bilbo Baggins",
 "email"=>"bilbo@lotr.com",
 "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,但我不确定如何。

控制器:

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

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 nested-forms nested-attributes


    【解决方案1】:

    如果其他人遇到同样的问题,我通过更改解决了这个问题:

    &lt;%= f.fields_for @network do |fn| %&gt;&lt;%= f.fields_for :network do |fn| %&gt; 并从用户模型中删除 :network 作为可访问属性。

    【讨论】:

    • 为此,您还必须在User 对象@user.networks.build 上构建network 对象。我假设您已经在控制器中执行了此操作,这就是它对您有用的原因。
    • 是的,我使用了@user.build_network,因为它是has_one 关联。
    • 谢谢!我整晚都在玩同样的问题,这个自我回答帮助了我!
    【解决方案2】:

    不确定,认为你需要:

    <%= f.fields_for @network, :network_attributes do |fn| %>
    

    【讨论】:

    • 不幸的是,我仍然遇到同样的异常。感谢您的建议。
    【解决方案3】:

    如果您将 :network 从模型中删除为可访问的,它肯定不会工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多