I have two models, Trip and Day, with a one-to-many relationship. For the time being I do not want to make Day an embedded document.
class Day
include MongoMapper::Document
...
key :trip_id, ObjectId
belongs_to :trip
end
class Trip
include MongoMapper::Document
...
key :day_ids, Array
many :days, :in => :day_ids
end
I would like to be able to create routes that look like this:
/trips/:trip_id/days/:index_of_day
Where :index_of_day
would be used to find the nth day in a trip @trip.days[:index_of_day]
, so a person could easily navigate to the first, second, etc. day of a trip.
Currently my route.rb file looks like this:
resources :trips do
resources :days
end
Which generates the default routes /trips/:trip_id/days/:day_id
.
One partway solution I had was to put in my route.rb file
match 'trips/:trip_id/day/:id' => 'days#show'
And then in my Day开发者_如何学Pythons Controller
def show
@day = Trip.find(params[:trip_id]).days(params[:id].to_i)
...
end
This sort of worked except all of the helpers like trip_day_path
automatically redirect using the day id, not the day index.
If you want your helpers to use the index instead of the day id, you can define to_param
in your Day
model. Rails calls to_param
on your object to find out what to put in the URL.
class Day
# ...
# many :in is for many-to-many, but you are using it for one-to-many
# either way, many :in doesn't have an inverse yet
def trip
Trip.first('day_ids' => self.id)
end
def to_param
trip.days.find_index(self)
end
end
You'll notice that's kind of hackish, which is a code smell.
精彩评论