我在Rails做饭订餐系统,我为用户,餐厅,餐和订单制作了模型,我不知道应该使用哪些关联将所有这些模型连接在一起。现在我的模型看起来像这样:
class User < ApplicationRecord
has_many :orders
has_many :restaurants, through: :orders
end
class Order < ApplicationRecord
belongs_to :user
belongs_to :restaurant
end
class Meal < ApplicationRecord
belongs_to :restaurant
end
class Restaurant < ApplicationRecord
has_many :orders
has_many :meals
has_many :users, through: :orders
end
现在,当我使用表格订购餐点并将此订单保存在数据库中时,我在日志中收到错误:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"+pwoJ/82k/2SiS7z4X4nVHyaKCMMfWCECQe6TufnkpNaW9PEgvlwxlf3skAH2QQupSLIoe81Z/I0CleL/m9cjw==", "orders"=>{"restaurant_id"=>"2", "meal_id"=>"2", "suggestions"=>""}, "commit"=>"Place your order"}
Unpermitted parameters: restaurant_id, meal_id
(0.1ms) begin transaction
(0.1ms) rollback transaction
Redirected to http://localhost:3000/
Completed 302 Found in 8ms (ActiveRecord: 0.2ms)
我的订单控制器如下所示:
class OrdersController < ApplicationController
def new
@order = Order.new
end
def create
@order = Order.new(order_params)
if @order.save
redirect_to root_path
flash[:success] = "Your order has been added"
else
flash[:danger] = "Error"
redirect_to root_path
end
end
private
def order_params
params.require(:orders).permit(:restaurant, :meal, :suggestions)
end
end
当我将def order_params更改为:
时 params.require(:orders).permit(:restaurant_id, :meal_id, :suggestions)
我正在
unknown attribute 'restaurant_id' for Order.
我认为它的错误关联是错误的,任何人都可以帮助我吗?
*更新*
现在,当我尝试保存订单时,我的日志中出现错误:
Started POST "/new_order" for 127.0.0.1 at 2016-12-19 11:18:50 +0100
Processing by OrdersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"nnDqY0FVzUslTJ1VoL57vnlO6aSTLcVuenT1GJwloJ8+txGAPJoucOAyAeZGGVjEoPYJJnBlwhhHeRjdha1ugw==", "orders"=>{"restaurant_id"=>"4", "meal_id"=>"26", "suggestions"=>""}, "commit"=>"Place your order"}
(0.1ms) begin transaction
Restaurant Load (0.1ms) SELECT "restaurants".* FROM "restaurants" WHERE "restaurants"."id" = ? LIMIT ? [["id", 4], ["LIMIT", 1]]
(0.1ms) rollback transaction
Redirected to http://localhost:3000/
Completed 302 Found in 6ms (ActiveRecord: 0.3ms)
*更新2 *
当我更改为@order.save!
时,我得到了:
Validation failed: User must exist
order.errors.inspect
我得到:
(0.2ms) rollback transaction
No template found for OrdersController#create, rendering head :no_content
Completed 204 No Content in 97ms (ActiveRecord: 1.8ms)
我使用omniauth登录之前,用户可以订餐,这只是注册或登录的方式。当我创建订单模型时,我使用user:references
,您认为这可能是一个原因?
答案 0 :(得分:0)
你说你有一个sign_in / sign_up,所以我假设你的控制器中有一个current_user
。
为了保存您的订单,您需要提供user_id
,这是一种方法
def order_params
params.require(:orders).permit(:restaurant, :meal, :suggestions)
.merge(user_id: current_user.id)
end