所以我觉得布局非常简单。我的配置路由是:
resources :webcomics
match '/webcomics/first' => 'webcomics#first', :as => :first
match '/webcomics/random' => 'webcomics#random', :as => :random
match '/webcomics/latest' => 'webcomics#latest', :as => :latest
控制器:
def show
@webcomic = Webcomic.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @webcomic }
end
end
def first
@webcomic = Webcomic.order("created_at ASC").first
respond_to do |format|
format.html { render 'show'}
format.json { render json: @webcomic }
end
end
导航栏:
<%= link_to first_webcomics_path, :rel => "tooltip", :title => "first comic" do %>
formatting in here
<% end %>
当我点击此链接时,它会将我发送到正确的路径/ webcomics /首先,但它给了我错误
Routing Error
No route matches {:action=>"edit", :controller=>"webcomics"}
我想知道怎么去'编辑',不管这条消息是完全错的,我都有编辑,但为什么要尝试去编辑动作。
def edit
@webcomic = Webcomic.find(params[:id])
end
佣金路线的结果:
first_webcomics GET /webcomics/first(.:format) webcomics#first
latest_webcomics GET /webcomics/latest(.:format) webcomics#latest
random_webcomics GET /webcomics/random(.:format) webcomics#random
webcomics GET /webcomics(.:format) webcomics#index
POST /webcomics(.:format) webcomics#create
new_webcomic GET /webcomics/new(.:format) webcomics#new
edit_webcomic GET /webcomics/:id/edit(.:format) webcomics#edit
webcomic GET /webcomics/:id(.:format) webcomics#show
PUT /webcomics/:id(.:format) webcomics#update
DELETE /webcomics/:id(.:format) webcomics#destroy
root / webcomics#index
答案 0 :(得分:3)
将这三个match
规则放在resources
行之上:
match '/webcomics/first' => 'webcomics#first', :as => :first
match '/webcomics/random' => 'webcomics#random', :as => :random
match '/webcomics/latest' => 'webcomics#latest', :as => :latest
resources :webcomics
原因在Ruby Guides: Routing中解释:
Rails路由按照指定的顺序进行匹配,所以如果你 有一个资源:上面的照片得到'照片/民意调查'的节目动作 资源行的路由将在获取行之前匹配。至 解决这个问题,将get行移到资源行上方,这样就可以了 首先匹配。
答案 1 :(得分:3)
路由是有序的;将match
es放在resources
上方。
那就是说,我会考虑adding those routes as RESTful actions:
resources :webcomics
collection do
get 'first'
get 'random'
get 'latest'
end
end
IMO这个更清洁一点,而且恰好很合适。
问题在于show
模板中的修改链接。编辑链接需要一个对象
编辑:
<%= link_to "edit", edit_webcomic_path(@webcomic) %>