2012-09-17 196 views
1

我有賭博的用戶。一次下注稱爲「Tipp」,用戶預測「tipp.tipp1」和「tipp.tipp2」中的匹配得分。Rails - 嵌套表格

我的表單有問題,應該保存用戶的「tipps」。

使用下面的代碼,我得到了「無法批量分配受保護的屬性:tipp」,儘管我已經設置了「accep_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)的竅門

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 %> 

回答

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 

古德勒克

+0

哇,非常感謝!你的第一個建議似乎有效:D – marius2k12