我们正在开发一个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非常新,所以任何帮助将不胜感激。非常感谢!
如果'旅行'不是嵌套的资源,你的生活会更容易一些。它不需要嵌套,还没有。 –