我正在使用ruby中的餐馆系统,目前正在按照现在设置的方式设置故障单控制器,每次用户点击添加到故障单时,它每次都会创建一个新故障单。我想要它,所以当用户单击添加到票证时,它会检查数据库中是否存在票证,如果不存在,则会创建一个新票证,如果存在,则会添加到同一票证。我不太确定如何处理它。
class TicketController < ApplicationController
def addToTicket
session[:tableID] = "15"
unless defined? check
check = Ticket.create(
table: session[:tableID],
tax: "8.25",
tstatus: 0
)
session[:ticket] = check
puts("**********Ticket created************")
redirect_to guest_path
else
check.orderItems.create(
item: (MenuItem.find_by id: params[:item_id]),
ingredients: params[:good_ingredients],
notes: params[:notes],
istatus: 0
)
session[:ticket] = check
puts("**************Ticket added to***********")
redirect_to guest_path
end
end
答案 0 :(得分:0)
您在模型中使用validations执行此操作:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :tickets
end
#app/models/ticket.rb
class Ticket < ActiveRecord::Base
belongs_to :user
belongs_to :table
validates :table, uniqueness: { scope: :user } # You didn't provide much context so this is quite generic
end
#app/models/table.rb
class Table < ActiveRecord::Base
has_many :tickets
has_many :users, through: :tickets
end
这允许您使用以下内容:
#config/routes.rb
resources :tables do
resources :tickets
end
#app/controllers/tickets_controller.rb
class TicketsController < ApplicationController
def new
@table = Table.find params[:table_id]
@ticket = current_user.tickets.new(table: @table)
end
def create
@table = Table.find params[:table_id]
@ticket = current_user.tickets.new ticket_params
@ticket.save
end
private
def ticket_params
params.require(:ticket).permit(:tax, :tstatus, :table_id).merge(table_id: @table.id)
end
end
在控制器中输出(puts
)并不是一个好主意...除非你喜欢检查你的日志。
我认为您正在尝试调用flash
方法:
def create
flash[:success] = "Ticket Created"
end
-
您还需要确保从您的观看中调用正确的操作 ...
您目前正在使用addToticket
(应该在snake_case
中) - 相当于update
。我建议您独立使用new/create
和update
操作,而不是您拥有的内容:
#app/controllers/tables_controller.rb
class TablesController < ApplicationController
def show
@table = Table.find params[:id]
@ticket = current_user.tickets.find_by(table_id: params[:id]) || current_user.tickets.new(table: @table)
end
end
#app/controllers/tickets_controller.rb
class TicketsController < ApplicationController
def create
@table = Table.find params[:id]
@ticket = current_user.tickets.new ticket_params
redirect_to @table if @ticket.save
end
def update
@table = Table.find params[:id]
@ticket = current_user.tickets.new ticket_params
## more logic here
redirect_to @table if @ticket.save
end
private
def ticket_params
params.require(:ticket).permit(:tstatus, :etc, :etc).merge(table_id: @table.id)
end
end
#app/views/tables/show.html.erb
<%= form_for [@table, @ticket] do |f| %>
<%= f.text_field :tstatus %>
....
<%= f.submit %>
<% end %>
上面将调用一个表单,并根据Table
模型用适当的字段填充它。 真的很酷的事情是,如果你设置它,如果没有票证,一个&#34;新&#34;将调用模型的实例,将提交内容发送到create
操作,否则update
。