Question

In my db there are a lot of users with invalid data (without mobile number). Because I added mobile presence validation just now. When I'm trying to add new event, I get error messages "Users mobile number must be in ... format". How I can skip user validation when creating events?

event.rb

class Event < ActiveRecord::Base
  has_many :participations
  has_many :users, :through => :participations
end

user.rb

class User < ActiveRecord::Base
  has_many :participations
  has_many :events, :through => :participations
end

events_controller.rb

 def create
    @event = Event.new(event_params)

    respond_to do |format|
      if @event.save
        format.html { redirect_to events_path, notice: 'Event was successfully created.' }
      else
        format.html { render action: 'new' }
      end
    end
  end

_form.html.erb

 <%= form_for @event, :html => {:class => 'row'} do |f| %>
      <%= f.error_messages %>

      <%= f.label :name %>
      <%= f.text_field :name %>

      <%= f.label :user_ids, "Participants" %>
      <%= f.collection_select :user_ids, User.all, :id, :name, {}, { :multiple => true } %>

      <%= clear %>

      <%= f.submit 'Save' %>
    <% end %>
Was it helpful?

Solution

Set validate: false in Event has_many :users association

class Event < ActiveRecord::Base
  has_many :participations
  has_many :users, :through => :participations, validate: false
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top