Search code examples
ruby-on-railsstrong-parameters

Strong parameter error when creating a new object


This is what I am trying to do here. I call a function test from user controller. and inside the test function I initialize a new article object like this article = new Article. But this gives me error

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

I have following code

users_controller

def create
 User.test
end

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

User model

class User

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

end

I know this question has been asked and answered lots of time but I could not find anything that matches with my problem or a solution for this. So please tell me how to save the article object inside user model call.


Solution

  • How is article = new Article even working? Oh I see. its calling Class#new and then passing in Class definition of itself... so it compiles. but its still not doing what you think it is. Try article = Article.new

    Also, your assignment inside the User model has no bearing on the controller user_params method which sanitizes your parameters