Rails验证不适用于habtm

时间:2012-05-06 07:47:45

标签: ruby-on-rails nested-forms nested-resources

现在我有以下几点:

model =>用户(姓名,电子邮件)

has_and_belongs_to_many :trips

model =>旅行(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

从代码中可以看出,trip模型对dest1和dest2进行了验证,但它没有显示错误。控制器和视图定义如下:

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 %>

1 个答案:

答案 0 :(得分:-1)

根据rails guide on presence 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