Rails 5如何配置双参数(名+姓)自定义URL
Got it! Let's get your URLs showing both first and last names for pilots. Here's how to adjust your setup step by step:
1. Update the to_param Method in Your Pilot Model
This method determines what string gets used as the URL parameter. Instead of returning just first_name, we'll combine first and last names with a clean hyphen separator, and use parameterize to ensure the string is URL-safe (it replaces spaces or special characters with hyphens):
def to_param "#{first_name.parameterize}-#{last_name.parameterize}" end
Example: If a pilot has first_name: "John" and last_name: "Doe", this will generate a URL segment like john-doe.
2. Adjust Your Route Configuration
Update the resources route to accept the combined name parameter, and tweak the constraints to match the hyphen-separated format (you can make this as strict or loose as needed):
resources :pilots, param: :full_name, constraints: { full_name: /[a-zA-Z\-]+/ }
param: :full_namerenames the parameter to something descriptive (instead of the default:idor your old:first_name).- The constraint
[a-zA-Z\-]+matches letters and hyphens—if you need to allow apostrophes (e.g.,O'Connor), adjust it to[a-zA-Z\-\']+. If you don't want strict validation, you can keep/.*/but the stricter regex helps avoid invalid URLs.
3. Update Your Controller's show Action
When a user visits /pilots/john-doe, Rails will pass john-doe as params[:full_name]. You'll need to split this back into first and last names to find the correct pilot:
def show # Split the parameter into two parts (in case last names have hyphens, like "van-der-sar") first_name_slug, last_name_slug = params[:full_name].split('-', 2) # Convert the slug back to title case (or match how names are stored in your database) @pilot = Pilot.find_by( first_name: first_name_slug.titleize, last_name: last_name_slug.titleize ) end
Note: Adjust the matching logic to fit how you store names in your database. If you store lowercase names, use downcase instead of titleize.
That's it! Now your pilot URLs will look like your-app.com/pilots/john-doe and correctly map to the right record.
内容的提问来源于stack exchange,提问作者dgreen22

