Rails - 嵌套表单

时间:2012-09-17 08:29:56

标签: ruby-on-rails

我有用户在比赛上下注。单个投注称为“Tipp”,用户在“tipp.tipp1”和“tipp.tipp2”中预测匹配分数

我的表单存在问题,应该保存用户的“tipps”。

使用下面的代码,我得到“无法大量分配受保护的属性:tipp”,尽管我设置了“accepts_nested_attributes_for:tipps”和“attr_accessible:tipps_attributes”。

我希望我已经提供了所有必要的代码。在此先感谢您的帮助!

以下是参数输出:

参数:

{
 "utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"mPPpCHjA3f/M2l1Bd3ffO1QUr+kdETGkNE/0CNhbJXE=",
 "user" =>{
          "tipp"=>{
                    "6"=>{"tipp1"=>"4","tipp2"=>"6"},
                    "7"=>{"tipp1"=>"-1","tipp2"=>"-1"},
                    "8"=>{"tipp1"=>"-1","tipp2"=>"-1"}
                  }
            },
 "commit"=>"Update User",
 "user_id"=>"1"
}

缩短代码:

控制器:

1)用户

class UsersController < ApplicationController

def edit_tipps
    @user = current_user
end

def update_tipps
    @user = current_user
    if @user.update_attributes(params[:user])
        flash[:notice] = "success (maybe)"
        redirect_to user_edit_tipps_path(@user)
    else
        flash[:error] = "errors"
        redirect_to user_edit_tipps_path(@user)
    end
end

型号:

1)用户

class User < ActiveRecord::Base 
attr_accessible :email, :password, :password_confirmation, :tipps_attributes

has_many :tipps
accepts_nested_attributes_for :tipps
end

2)Tipps

class Tipp < ActiveRecord::Base
attr_accessible :match_id, :points, :round_id, :tipp1, :tipp2, :user_id

belongs_to :user
end

我的表格:

<%= form_for @user, :url => { :action => "update_tipps" }  do |user_form| %>
    <% @user.tipps.each do |tipp| %>
    <%= user_form.fields_for tipp, :index => tipp.id do |tipp_form|%>
        <%= tipp_form.text_field :tipp1 %><br/>
        <%= tipp_form.text_field :tipp2 %><br/>
    <% end %>
    <% end %>
    <%= submit_or_cancel(user_form) %> 
<% end %>

1 个答案:

答案 0 :(得分:2)

而不是做你做的, 你可以试试:

1。 而不是:

  <% @user.tipps.each do |tipp| %>
  <%= user_form.fields_for tipp, :index => tipp.id do |tipp_form|%>

我会这样做:

  <%= user_form.fields_for :tipps do |tipp_form| %>

或者: 2。

class User < ActiveRecord::Base 
attr_accessible :email, :password, :password_confirmation, :tipps_attributes, :tipps

古德勒克