我正在使用Rails 3.2.2,但收到以下错误。下面的表单使用嵌套模型,我无法找到几天来我一直试图找到的错误来源。
ActiveModel::MassAssignmentSecurity::Error in UsersController#create
Can't mass-assign protected attributes: blog
app/controllers/users_controller.rb:17:in `new'
app/controllers/users_controller.rb:17:in `create'
表单变量
class HomeController < ApplicationController
def index
@user = User.new
@blog = @user.blogs.build
end
end
用户表单
<%= form_for @user do |f| %>
<%= f.text_field :email, :class => 'textbox', :value => 'Email' %><br/><br/>
<%= f.password_field :password, :class => 'textbox', :value => 'Password' %><br/><br/>
<%= f.fields_for :blog do |b|%>
<%= b.text_field :url, :class => 'textbox', :value => 'Blog URL' %></br></br>
<% end %>
<%= image_submit_tag("signup.png") %> <br/>
<% end %>
用户控制器
class UsersController < ApplicationController
def create
@user = User.new(params[:user]) ############## << RUNTIME ERROR #############
if @user.save
flash[:success] = "Welcome!"
render 'user/success'
else
render 'home/index'
end
end
博客模型
class Blog < ActiveRecord::Base
belongs_to :user
attr_accessible :url, :type, :blog_id
validates :url, :presence => true
end
用户模型
class User < ActiveRecord::Base
has_many :blogs
has_many :posts
accepts_nested_attributes_for :blogs, :allow_destroy => true
attr_accessible :email, :password, :user_id, :blogs_attributes
end
模式
create_table "blogs", :force => true do |t|
t.integer "user_id"
t.string "url"
t.string "type"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "email"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "password_digest"
t.string "remember_token"
end
尝试在博客上添加 s。应该是博客。
<%= f.fields_for :blogs do |b|%>
<%= b.text_field :url, :class => 'textbox', :value => 'Blog URL' %></br></br>
<% end %>