0

for now i've got followings:

model => User (name, email)

has_and_belongs_to_many :trips

model => Trip (dest1, dest2)

has_and_belongs_to_many :users

validates :dest1, :dest2, :presence => true

model => TripsUsers (user_id, trip_id) (id => false)

belongs_to :user

belongs_to :trip

As you see from the code, trip model has validation on dest1, and dest2, but it's not showing up an errors. Controller and view defined as follow:

trips_controller.rb

  def new
    @user = User.find(params[:user_id])
    @trip = @user.trips.build
  end

  def create
    @user = User.find(params[:user_id])
    @trip = Trip.new(params[:trip])
    if @trip.save
      @trip.users << @user
      redirect_to user_trips_path, notice: "Success"
    else
      render :new
    end
  end

_form.html.erb

<%= simple_form_for [@user, @trip] do |f| %>
    <%= f.error_notification %>
    <%= f.input :dest1 %>
    <%= f.input :dest2 %>
    <%= f.submit "Submit" %>
<% end %>
Said Kaldybaev
  • 9,380
  • 8
  • 36
  • 53

1 Answers1

-1

According to the rails guide on presence validation, it can't be used with associated objects. Try to use a custom validation:

validate :destinations_presence

def destinations_presence
  if dest1.nil? 
    errors.add(:dest1, "missing dest1")
  elsif dest2.nil?
    errors.add(:dest1, "missing dest2")
  end
end
Baldrick
  • 23,882
  • 6
  • 74
  • 79
  • You're probably referring to: *If you want to be sure that an association is present, you’ll need to test whether the foreign key used to map the association is present, and not the associated object itself.* part. This is a performance recommendation to eliminate extra DB lookup. But you're free to validate associated object. – jdoe May 06 '12 at 10:56
  • thanks Baldrick, adding custom method didn't work, it just creates empty record, i tried also blank? instead of nil? but the result is same like with presence: true – Said Kaldybaev May 06 '12 at 10:59