You can read more about this in the arkency blog You cannot use the contexts for distinguishing between create and update which is their default behavior.While this code solves our problem at hand, there are some new problems introduced with this approach: Payment_params = params.require(:user).permit(:payment_type, :update_payment) User_address_params = params.require(:user).permit(:name, :street, :zip_code, :update_address) An implementation for our problem could look like the following:Ĭlass UsersController < ApplicationController While I would tend to use form objects in a real world scenario I do not want to introduce another gem to this example code and will therefore go with validation contexts. Using validation contexts within the model to separate the validations for the two use cases.You would then move the validation logic to these two objects and they would validate user input before saving the model. Adding an additional layer by using two form objects (e.g.Splitting the user model into separate models each containing just the data that is present within one form.There are multiple ways to circumvent the problem mentioned above: The reason for these problems is that ActiveRecord always validates and saves the model as a whole and has no notion of the current action that the user is performing. We add some more validations to our model:Ĭlass User AddressServiceValidator is always run even if the user only entered her payment details. Let’s say we want to build a second page within our application that lets the user enter her preferred payment type that can be chosen from a predefined list. While this approach works well in approaches where a user alters the model as a whole, it can be insufficient in more complex cases. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain." The shortcomings of the ActiveRecord approachĭefining the validations per model is an explicit design choice of the authors of ActiveRecord, as stated within the official RailsGuides: "Model-level validations are the best way to ensure that only valid data is saved into your database. As a side effect, it stores all errors in a property of the user object which allows for displaying detailed error messages to the user when the edit view is rendered. Class UsersController calls under the hood which returns whether the validation succeeded or not.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |