无法在ActiveRecord中创建新记录

时间:2014-02-17 07:26:23

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

我正在尝试从Rails 3迁移到Rails 4.我不知道为什么,但是当我尝试创建新记录时,我收到错误消息:

2 errors prohibited this group from being saved:
    Name can't be blank
    Tags can't be blank

这是一个控制器代码:

  def create
    @user = UserData.find_by_login(session[:cuser])
    @group = @user.groups.new(params[:group])


    puts "======================="
    p @user
    p params
    p params[:group]
    p @group
    p "========"
    p @user.groups

    respond_to do |format|
      if @group.save
        format.html { redirect_to(@group, :notice => 'Group was successfully created.') }
        format.xml  { render :xml => @group, :status => :created, :location => @group }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @group.errors, :status => :unprocessable_entity }
      end
    end
  end

这是一个控制台日志:

=======================

我看到@user变量已被初始化:

#<UserData id: 1, login: "demas", hashed_password: "e55105f41cd0391b440176a1cd5b14c2732410ca", salt: "xnqKXtOgwO", created_at: "2014-02-17 06:18:08", updated_at: "2014-02-17 06:18:08", last_login: "2014-02-16 20:00:00", login_count: 1, admin: 0>

我在参数中有分组:

{"utf8"=>"✓", "authenticity_token"=>"2qxvqJh0nrJiZt+7xvI0lZjA83Z+hw/GKzwrNlqEh44=", "group"=>{"name"=>"112", "tags"=>"2", "stop_tags"=>"", "download_on_refresh"=>"0", "site_id"=>"1"}, "commit"=>"Create Group", "action"=>"create", "controller"=>"groups"}
{"name"=>"112", "tags"=>"2", "stop_tags"=>"", "download_on_refresh"=>"0", "site_id"=>"1"}

但是当我打电话给@ user.groups.new()时,我得到空组:

#<Group id: nil, name: nil, tags: nil, created_at: nil, updated_at: nil, user_data_id: 1, site_id: nil, stop_tags: nil, position: nil, last_sync: nil, download_on_refresh: nil>

我已经检查了@ user.groups,因为我看到关系正常:

"========"
  Group Load (0.3ms)  SELECT "groups".* FROM "groups" WHERE "groups"."user_data_id" = ?  [["user_data_id", 1]]
#<ActiveRecord::Associations::CollectionProxy [#<Group id: nil, name: nil, tags: nil, created_at: nil, updated_at: nil, user_data_id: 1, site_id: nil, stop_tags: nil, position: nil, last_sync: nil, download_on_refresh: nil>]>
   (0.1ms)  begin transaction

为什么@ user.groups.new()不创建新记录?

提前致谢

1 个答案:

答案 0 :(得分:3)

Rails实现了'强参数',因此直接使用params [:group]创建模型将无法正常工作。您需要允许控制器接受这些参数以进行模型创建。

您的代码:

def create
    @user = UserData.find_by_login(session[:cuser])
    @group = @user.groups.new(params[:group])  
    .
    .
end

可能的解决方案:

def create
    @user = UserData.find_by_login(session[:cuser])
    @group = @user.groups.new(group_post_params)
    .
    .
end

private
    def group_post_params
        params.require(:group).permit(:name, :tags, etc, etc)
    end