简体   繁体   中英

Rails 3: how to code a route path

I'm creating a rails app and I can't figure out or find answer for this problem.

What is the route for:

@example = Example.find_by_notId(params[:notId])

I want my route to look better then /example/1 and would rather have it read /notId (where notId would be title or some other non-ID int). Normally I would use show_path but in my html <%= link_to image_tag(pic), show_path(example) %> doesn't work. Here is my code and it works when I hard code it into the URL (localhost:3000/notId) but I need a way to route it through a link. Any ideas?

Show

def show
   @example = Example.find_by_title(params[:title])
end

Routes

match '/:notId', to: 'example#show', via: 'get'

_example.html.erb

<div class="example">
 <% Movie.all.each do |example| %>
  <%pic = example.title + ".jpg"%>
  <%= link_to image_tag(pic), show_path(example) %>
 <% end %>
e</div>

You probably need to override the :id param in your routes:

resources :examples, param: :title

This will generate routes like:

/examples/:title
/examples/:title/edit

Then in your views:

example_path(example.title)

Alternatively, you can change the method to_param (used for building urls) in your model:

class Example < ActiveRecord::Base
  def to_param
    title
  end
end

This allows you to keep using example_path(example) (without .title )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM