现在我有以下几点:
模型 => 用户(姓名、电子邮件)
has_and_belongs_to_many :trips
模型 => 行程(dest1, dest2)
has_and_belongs_to_many :users
validates :dest1, :dest2, :presence => true
模型 => 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 %>