Edw*_*año 3 parameters ruby-on-rails parameter-passing nested-attributes
我正在开发一个非常基本的练习应用程序,用户可以在其中创建多个引用.我遇到的问题是我无法更新我的报价.我有很多东西,并在谷歌和其他问题阅读,但无法弄清楚我做错了什么.这是我的代码:
#User Model
class User < ActiveRecord::Base
has_many :quotations, :dependent => :destroy
attr_accessible :quotations
accepts_nested_attributes_for :quotations, :allow_destroy => true
end
#Quotations Model
class Quotation < ActiveRecord::Base
attr_accessible :quote_text, :author, :quote_type, :category, :tags, :user_id
belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)
class QuotationsController < ApplicationController
before_filter :get_user
def get_user
@user = User.find(params[:user_id])
end
def edit
@quotation = @user.quotations.find(params[:id])
end
def update
@quotation = @user.quotations.find(params[:id])
if @quotation.update_attributes(params[:id])
redirect_to user_quotation_path :notice => "Successfully updated quotation."
else
render :action => 'edit'
end
end
end
Run Code Online (Sandbox Code Playgroud)
您将错误的params散列传递给update_attributes调用.它应该是
if @quotation.update_attributes(params[:quotation]).
澄清,通过:id或:quotation没有做任何特别的事情. Ruby中的符号只是不可变的字符串.所以使用:id或:quotation相当于传递字符串"id"或"quotation". params[]是页面发布的所有表单参数的哈希映射.
在params哈希中,有一个您传递的类型的键(在本例中quotation),其具有另一个哈希值,其中包含与视图中的引用关联的所有已发布字段以及这些字段的值.
params散列中的ID,控制器和操作值来自url的路由值.
例如
params[] =
{
:controller => 'quotations',
:action => 'edit',
:id => '1',
:quotation =>
{
:quote_text=> "Blah",
:author=> "Steve",
:quote_type=> "1",
:user_id=> "6"
}
}
Run Code Online (Sandbox Code Playgroud)