我們正在開發一個Ruby on Rails 3.2的社交網絡原型。 該系統是爲旅行者設計的,所以每個用戶都必須有很多旅行。 我們創建了旅行模型,並在旅行模型和用戶模型中分別設置了與「belongs_to」和「has_many」的關聯。 我們創建了一個表單創建一個特定的用戶一個新的旅程,但是,當我們提交表單系統返回此錯誤:Ruby On Rails - 路由錯誤 - 無路由匹配{:action =>「show」,:controller =>「trips」}
Routing Error
No route matches {:action=>"show", :controller=>"trips"}
我們知道,此行已成功創建,因爲如果我們輸入網址http://localhost:3000/users/1/trips/1我們看到了創建的旅程。
這是代碼:
trip.rb
class Trip < ActiveRecord::Base
attr_accessible :name, :departure, :arrive, :trip_objects
belongs_to :user
default_scope order: 'trips.created_at DESC'
validates :user_id, presence: true
validates :name, :departure, :arrive, :trip_objects, presence: true
end
trips_controller.rb
def create
# refine the trip variable content with the data passed by the sign up form
@trip = current_user.trips.build(params[:trip])
if @trip.save
# handle a successful save
flash[:success] = 'Trip created!'
redirect_to user_trip_path
else
@trip = []
redirect_to home_path
end
end
def index
@user = User.find(params[:user_id])
# get all her trips
@trips = @user.trips.paginate(page: params[:page])
end
到routes.rb中
resources :users do
member do
get :info
end
resources :trips, only: [:new, :create, :index, :show, :destroy]
end
而且在trips_controller.rb - 創建行動,如果我們重定向到user_trips_path代替user_trip_path的我們得到正確創建人次的指標,相應的路線。
給您路線
info_user GET /users/:id/info(.:format) users#info
user_trips GET /users/:user_id/trips(.:format) trips#index
POST /users/:user_id/trips(.:format) trips#create
new_user_trip GET /users/:user_id/trips/new(.:format) trips#new
user_trip GET /users/:user_id/trips/:id(.:format) trips#show
DELETE /users/:user_id/trips/:id(.:format) trips#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
你有這個問題的任何想法?我們對Rails非常新,所以任何幫助將不勝感激。非常感謝!
如果'旅行'不是嵌套的資源,你的生活會更容易一些。它不需要嵌套,還沒有。 –