How do I able to create a user before initialization of model

有些话、适合烂在心里 提交于 2019-12-12 02:15:21

问题


In my model(Product) i have a validation, that each product should have a valid owner (login_id of user)

validates_presence_of :owner
validates_inclusion_of :owner, :in => User.first.login_id, :message => "%{value} is not a valid owner name"

I am trying to create product mock object using factory girl

for creating a new product I need login_id of a user. to do so i have create a user.

up to this every thing is ok, but when i am trying to create a Product using that user's login_id product is not create, and displaying validation message ("User1 is not a valid owner name").

After digging into deeper i found that

  1. Problem arise from validation in my model.
  2. I have a validation (validates_inclusion_of :owner, :in => User.first.login_id) which initialize before creating the mock user in factory.rb, (up to that time no user is created in database, user is created after initialization of model when it execute factory.rd )

My question is: 1. How do I able to create a user before initialization of model.


回答1:


Can you not create a user object, and then pass that object to your product factory? This should create a valid user and then supply it through the owner association and make the product valid.

user = Factory(:user, :name => "User1")
product = Factory(:product, :owner => user)

This user apparently has to be the first user too? So if you have existing user objects then you can try clearing all users before you create the first one.

User.delete_all



回答2:


I solve this problem as follows:

In my model I have replaced the 'Rails validation' by writing Custom validation method. This custom validation method will be called at the time of creating 'Product'.

validates_presence_of :owner
validate :owner_should_be_registered_user

def owner_should_be_registered_user
    if !User.all_user.include? owner and !owner.nil?
      errors.add(:owner, "is not a valid user")
    end
  end


来源:https://stackoverflow.com/questions/7316019/how-do-i-able-to-create-a-user-before-initialization-of-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!