需要帮助整理ruby on rails预订网页应用

时间:2014-04-16 01:39:13

标签: ruby-on-rails ruby

我正在尝试使用ruby on rails编写预订网络应用程序,我遇到了一些麻烦。我创建了以下模型:     +用户     +餐厅     +表     +保留

我已经建立了关系,但我很难将用户和表格分配给新的预订。有没有类似于current_user我可以用来匹配表到预订?餐厅也是如此 - 我如何确保用户在新餐厅时设置桌子?

由于

2 个答案:

答案 0 :(得分:3)

您可以使用:through设置多对多关系,此处为文档的link

你可以这样做。

用户模型:

class User < ActiveRecord::Base
  has_many :reservations
  has_many :tables, through: :reservations
end

表格型号:

class Table < ActiveRecord::Base
  has_many :reservations
  has_many :users, through: :reservations
end

预订模式:

class Reservation < ActiveRecord::Base
  belongs_to :user
  belongs_to :table
end

然后,您只需为以下用户创建一个新表:user.table = some_table

答案 1 :(得分:0)

你会做得更好:

#app/models/reservation.rb
Class Reservation < ActiveRecord::Base
    belongs_to :user
    belongs_to :table
end

#app/models/user.rb
Class User < ActiveRecord::Base
    has_many :reservations
    has_many :tables, through: :reservations
end

#app/models/restaurant.rb
Class Restaurant < ActiveRecord::Base
    has_many :tables
    has_many :reservations, through: :tables
end

#app/models/table.rb
Class Table < ActiveRecord::Base
    belongs_to :restaurant

    has_many :reservations
    has_many :users, through: :reservations
end

这意味着您将能够使用<< ActiveRecord method将您的用户/表添加到预订集合中,或者直接创建预订:

#app/controllers/reservations_controller.rb
Class Reservation < ApplicationController
    def create
       reservation = Reservation.new(reservation_params)
       reservation.save
    end

    private

    def reservation_params
        params.require(:reservation).permit(:user_id, :table_id)
    end
end