Creating a table-less model with validation for registration, don't want to jam multiple models

StackOverflow https://stackoverflow.com/questions/23528293

Domanda

I have a registration form that has fields from 3 models.

I know you can somehow create a form based on multiple models, but I was thinking of just creating another model for this form and then if validation passes just create the other models by myself.

How can I create a table-less model, I am using Rails 4.1 (latest).

Is this a common practise or should I just learn how to create a form that has 3 models in it?

Rails casts has a sample like:

class Message
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :content

  validates_presence_of :name
  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
  validates_length_of :content, :maximum => 500

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end
end

So what would be a clean way of using this approach? This is what I am thinking so far:

  1. write tests on this tabless model to ensure the validations are how I want them.
  2. when the form posts, verify .valid? is true.
  3. if it is valid, then use the fields to initialize my other models and verify they are all valid.
  4. save all the models
  5. write tests to make sure the tabless-model can correctly initialize the other models so they can be saved correctly.

Any best practises or comments on this approach?

È stato utile?

Soluzione

you could look into reform.

using ActiveModel is even easier, make sure to pass the ActiveModel::Lint tests.

other than that, what you described is the way to go.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top