I am a beginner at Ruby on Rails. Currently, I have the following problem: I have a class Game that has an array of pictures and sentences alternating. I want that a user who creates a new Game is required to give one starting picture OR sentence. If he doesn’t do so I’d like to not save the newly created game to the data base.
class Game < ActiveRecord::Base
has_many :sentences
has_many :paintings
validates_inclusion_of :starts_with_sentence, :in => [true, false]
[...]
end
My approach was that on /games/new, the user has to give either one painting or one sentence to begin with, but I am unsure how to enforce this, especially how to create and save a child object along with the parent object in one step.
So you’ve got two questions. The first (though second in your question) is “how to create and save a child object along with the parent object in one step.” This is a common pattern and looks something like this:
Then in, say,
views/games/new.html.erbyou can have something like this:When this form is submitted Rails will interpret the
POSTparameters and you’ll end up with aparamsobject that looks something like this:And finally, in the controller that receives those
params:That’s a very very high-level peek at what you’ll be doing. Nested attributes have their very own section in the docs.
Your other question is how to enforce this. To do that you’ll need to write some custom validations. There’s two ways to do this. The simplest way is with
validate, e.g.:The other method is creating a custom validator class which lives in another file. This is particularly useful if you need to do a lot of custom validations or if you want to use the same custom validations on several classes. This, along with the single method, er, method, are both covered in the Validations Rails Guide.
Hope that’s helpful!