我正在尝试构建的功能允许用户访问一家餐馆。从两个ID创建轨道记录
我有用户,位置和餐厅模型。 地点有很多餐厅。
我创建了一个带有user_id和restaurant_id属性的Visits模型,以及一个带有create和destroy方法的visits_controller。
事情是,我无法创建一个实际访问记录。有关我如何完成此任务的任何想法?或者我是以错误的方式去解决问题。
路由错误
No route matches {:controller=>"restaurants", :location_id=>nil}
代码:
路线:
location_restaurant_visits POST /locations/:location_id/restaurants/:restaurant_id/visits(.:format) visits#create
location_restaurant_visit DELETE /locations/:location_id/restaurants/:restaurant_id/visits/:id(.:format) visits#destroy
型号:
class Visit < ActiveRecord::Base
attr_accessible :restaurant_id, :user_id
belongs_to :user
belongs_to :restaurant
end
查看:
<% @restaurants.each do |restaurant| %>
<%= link_to 'Visit', location_restaurant_visits_path(current_user.id, restaurant.id), method: :create %>
<% @visit = Visit.find_by_user_id_and_restaurant_id(current_user.id, restaurant.id) %>
<%= @visit != nil ? "true" : "false" %>
<% end %>
控制器:
class VisitsController < ApplicationController
before_filter :find_restaurant
before_filter :find_user
def create
@visit = Visit.create(params[:user_id => @user.id, :restaurant_id => @restaurant.id])
respond_to do |format|
if @visit.save
format.html { redirect_to location_restaurants_path(@location), notice: 'Visit created.' }
format.json { render json: @visit, status: :created, location: @visit }
else
format.html { render action: "new" }
format.json { render json: @visit.errors, status: :unprocessable_entity }
end
end
end
def destroy
@visit = Visit.find(params[:user_id => @user.id, :restaurant_id => @restaurant.id])
@restaurant.destroy
respond_to do |format|
format.html { redirect_to location_restaurants_path(@restaurant.location_id), notice: 'Unvisited.' }
format.json { head :no_content }
end
end
private
def find_restaurant
@restaurant = Restaurant.find(params[:restaurant_id])
end
def find_user
@user = current_user
end
end
完美的,特别要感谢澄清PARAMS/HASH位。 – mLuby