问题
I have a has_one through relationship with a condition that connects trips and addresses in my app. Each trip has two addresses: the origin, and the destination. Addresses can be used in many different trips, and can be either origins or destinations.
In the app, trips and addresses are connected by a model called TripLocation, which as a Boolean column "destination" which sets whether the address is functioning as a destination for the trip or not. To see more about that relationship, see this previous question I asked about the same app: Has_many through in Rails while assigning different roles
I want app users to select from a list of possible addresses for the origin and the destination when they are creating a trip. Here is what I have, which I know is not correct:
<%= simple_form_form (@trip) do |f| %>
<%= f.error_notification %>
<%= f.input :origin, collection: Address.all, label_method: :kind, value_method: :id, label: "Starting address" %>
<%= f.input :destination, collection: Address.all, label_method: :kind, value_method: :id, label: "Ending address" %>
#other trip things here like date and time
<% end %>
(Eventually I will limit the address choice from Address.all but for now I'd like this version to work.)
When I try to submit from this form I get the following error message:
NoMethodError in TripsController#create
undefined method 'id' for "1":String
So this seems like it's expecting to have an object (with an id) rather than the string containing an object's id. I know what new entries should be appearing in the database to connect up everything correctly, but I'm not sure how to use rails to get there, and I'd appreciate any information to point me in the right direction.
Edit: Here is the code for the create action in trips_controller:
def create
@trip = Trip.new(trip_params)
if @trip.save
redirect_to @trip, notice: 'Trip was successfully created.'
else
render action: 'new'
end
end
and since this is Rails 4, trip_params is the following private method:
def trip_params
params.require(:trip).permit(:origin, :destination, :pickup_date, :pickup_time, :dropoff_date, :dropoff_time, :user_id, :company_profile_id, :vehicle_id)
end
Now I am wondering if I need to build a new TripLocation object in the controller, and then use a nested form to make both a Trip and a TripLocation at once?
来源:https://stackoverflow.com/questions/19739820/how-to-use-a-form-to-connect-has-one-through-relationship-with-condition