How do I able to create a user before initializati

2019-09-13 10:11发布

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.

2条回答
男人必须洒脱
2楼-- · 2019-09-13 10:58

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
查看更多
你好瞎i
3楼-- · 2019-09-13 11:00

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
查看更多
登录 后发表回答