4

我阅读了很多关于 `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

谢谢

4

3 回答 3

8

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

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

于 2011-02-17T23:55:05.800 回答
1

不确定,认为您需要:

<%= f.fields_for @network, :network_attributes do |fn| %>
于 2011-02-16T00:15:25.977 回答
0

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

于 2011-04-10T14:21:33.000 回答