使用form_for创建嵌套模型行

时间:2014-02-17 23:04:15

标签: ruby-on-rails ruby-on-rails-4

  • 每个“用户”都有一个“移动”。
  • 每个“Move”都有很多“邻居偏好”。

我想在“/ user /(:id)/ edit”页面上创建一个表单,让人们可以编辑“move”和“neighborhood_preferences”。

目前,表单正确显示。但是当我提交表单时,我收到此错误Move(#2168853040) expected, got ActionController::Parameters(#2158484920)

如何保存新动作和邻居偏好?

查看用户#edit

<%= form_for(@user) do |f| %>
  <%= hidden_field_tag "user[move][neighborhood_ids][]", nil %>

  <% @neighborhoods.each do |n| %>
    <%= check_box_tag "user[move][neighborhood_ids][]", 
        n.id, # the value to submit
        @user.move.neighborhood_ids.include?(n.id), # Check the box on load 
        id: dom_id(n) # add a unique category based on the object
    %>
    <%= label_tag dom_id(n), n.name %>
    <br/>
  <% end %>
  <%= f.submit "Save Changes" %>
<% end %>

用户控制器编辑

def edit
  @user = User.find(params[:id])
  @neighborhoods = Neighborhood.all
end



private 
    def user_params
      params.require(:user).permit(
        :email, 
        :age,
        :gender,
        :university,
        :grad_year,
        :occupation,
        :company,
        # Allow form to submit neighborhood_ids for a user's move.
        move: [neighborhood_ids: []]
      )
    end

模型

class User < ActiveRecord::Base
  # attr_accessible :provider, :uid, :name, :email
  validates_presence_of :name
  has_one :move
  accepts_nested_attributes_for :move, allow_destroy: true


class Move < ActiveRecord::Base
    belongs_to :user
    has_many :neighborhood_preferences
    has_many :neighborhoods, through: :neighborhood_preferences
    accepts_nested_attributes_for :neighborhood_preferences, allow_destroy: true
end

class NeighbhoodPreference < ActiveRecord::Base
  belongs_to :neighborhood
  belongs_to :move
end

0 个答案:

没有答案