创建新对象时出现强参数错误

时间:2017-01-20 19:13:58

标签: ruby-on-rails strong-parameters

这就是我在这里要做的。我从用户控制器调用功能测试。在测试函数内部,我初始化一个像这个article = new Article的新文章对象。但这给了我错误

ArgumentError in UsersController#create
When assigning attributes, you must pass a hash as an argument. 

我有以下代码

users_controller

def create
 User.test
end

private
def user_params
  params.require(:user).permit(:name, articles_attributes:[:content)
end

用户模型

class User

def self.test
  article = new Article
  article.attributes = {"content"=>"this is some sample content"}
  article.save
end

end

我知道这个问题已被提出并且回答了很多时间,但我找不到任何与我的问题或解决方案相符的内容。那么请告诉我如何在用户模型调用中保存文章对象。

1 个答案:

答案 0 :(得分:0)

article = new Article如何工作?原来如此。它调用Class#new然后传入自己的类定义......所以它编译。但它仍然没有做你认为的那样。试试article = Article.new

此外,您在User模型中的分配与控制器user_params方法无关,该方法会清理您的参数

相关问题