Search code examples
rubyif-statementclass-method

Putting if statement in Ruby create


Example.create(
  attribute1 = "asdf",
  attribute2 = "asdf2",
  attribute3 = "and 20 more attributes"
)

But how do I conveniently make variable2 = "qwer" if random_thing == "zxcv", without having to have two (nearly) identical create methods inside an if/else?


Solution

  • You can supply a block to the create method, which you can you use to conditionally "overwrite" attribute2:

    Example.create(attribute1: "asdf",
                   attribute2: "asdf2",
                   attribute3: "and 20 more attributes") do |e|
      e.attribute2 = "qwer" if random_thing == "zxcv"
    end
    

    Edit: I have found a more beautiful and elegant solution. So I replaced the initial approach with the version above.