简体   繁体   中英

Unable to create the model within its associated model

I have a User model which has_one Post model, which belongs_to User. Through a before_save callback, I want to create an (actually multiple, but this is another question) empty (or better, default like saying "This is my first post") Post, whenever a new user signs up. But the function below:

def create_post
  @post = Post.new(params[:post])
  @post.user = self
  @post.save

gives an error:

undefined local variable or method `params' for #

What might the problem be?

You don't have access to the params hash in the model.

You don't want to do this in an after_save callback, but in a after_create or before_create I'd say.

Also, I don't understand why a User has_one Post... especially if you want to create several.

In the callback:

  • if a user has_one :post

    self.create_post(default_values_hash)

  • if has_many :posts

    self.posts.create(default_values_hash)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM