将多个用户添加到单个记录Rails 5中

时间:2018-04-02 03:56:30

标签: ruby-on-rails activerecord ruby-on-rails-5

所以我有一个app rails 5,ruby 2.4.0。

我有卡车型号和用户型号。

当用户创建新的Truck时,他们需要添加所有者和驱动程序(两个用户)

创建此记录时,它会自动保存创建记录的用户。

现在,当我添加新卡车时,会保存用户ID并同时保存owner_id和driver_id。

当我尝试列出记录中的所有者,驱动程序和用户名时,他们互相写了,我现在也收到了这个错误:

Better Errors screenshot

我的卡车型号:

class Truck < ApplicationRecord
  has_many :users
end

我的用户模型:

class User < ApplicationRecord

  devise :invitable, :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :invitable

  has_many :trip_categories
  has_many :trucks

end

我的卡车控制器(显示动作):

class TrucksController < ApplicationController

  # GET /trucks/1
  # GET /trucks/1.json
def show
   @truck = Truck.find(params[:id])
   @truck.owner_id = User.find_by(params[:owner_id])
   @truck.driver_id = User.find_by(params[:driver_id])
   @truck.user = User.find_by(params[:user_id])
 end


  private
    # Use callbacks to share common setup or constraints between actions.
    def set_truck
      @truck = Truck.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def truck_params
      params.require(:truck).permit(:make, :model, :color, :vin, :unit_number, :owner_id, :driver_id, :user_id)
    end
end

很长一段时间以来,我做过这样的事情,我们将非常感谢任何帮助,如果需要其他任何帮助来解决这个问题,请告诉我。

编辑1:添加新错误的屏幕截图:

Better errors screenshot

2 个答案:

答案 0 :(得分:1)

has_many :users将一个实例方法users添加到Truck类。

您可以添加

等用户
@truck.users << user1
@truck.users << user2
@truck.users << user3
# or equivalently
@truck.users << [user1, user2, user3]

关于EDIT1,您应该has_many :users不添加user方法, 所以错误说它是未定义的。

答案 1 :(得分:1)

您应该在用户和卡车之间添加两个关系,如下所示

class User
  has_many :own_trucks, as: :owner, class_name: 'Truck'
  has_many :driving_trucks, as: :driver, class_name: 'Truck'
end

class Truck
  belongs_to :owner, class_name: 'User'
  belongs_to :driver, class_name: 'User'
  belongs_to :user, class_name: 'User' <-- added - Edited to provide full answer to solution
end



def create
  # @truck = Truck.new
  # @truck.owner = User.find(params[:owner_id])
  # @truck.driver = User.find(params[:driver_id])
  @truck = Truck.new(params.permit(:driver_id, :owner_id, :xxxx1, :xxxx2))
  @truck.save
end

def show
  @truck = Truck.find(params[:id])
end