Putting if statement in Ruby create

61 views Asked by At
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?

3

There are 3 answers

1
Fabian Winkler On BEST ANSWER

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.

1
spickermann On

Perhaps by using a ternary operator:

Example.create(
  attribute1 = "asdf",
  attribute2 = random_thing == "zxcv" ? "qwer" : "asdf2",
  attribute3 = "and 20 more attributes"
)

Or simplified:

Example.create("asdf", random_thing == "zxcv" ? "qwer" : "asdf2", "and 20 more attributes")
0
Genry Wood On

If your input parameters are a hash, you can just pass

Example.create(attributes)

Rails automatically create instance with provided params

If there are any values in the parameters that you want to avoid when creating the record, use the following

Example.create(attributes.except(:parameter_to_except)