【问题标题】:Setting a relationship between Users to access a resource设置用户之间的关系以访问资源
【发布时间】:2015-07-10 20:31:54
【问题描述】:

我正在自学 Rails,我正在尝试建立一种协作关系,就像 Github 将协作者添加到项目中一样。我的模型如下所示:

class Restaurant < ActiveRecord::Base
    has_many :employees
    has_many :users, through: :employees
end

class User < ActiveRecord::Base
  has_many :employees
  has_many :restaurants, through: :employees
end

class Employee < ActiveRecord::Base
    belongs_to :restaurant
    belongs_to :user
end

employee 表还有一个 user_type 列来处理项目(餐厅)内的权限。我不知道如何让我的employee_controller 设置这种关系。用户主键是 :email 所以我猜一个表单应该能够接收 :email 参数,检查输入电子邮件的用户是否存在,并将关系添加到员工表中。

我希望能够做这样的事情:

Restaurant_A = Restaurant.create(restaurant_params)
User_A.restaurants = Restaurant_A
Restaurant_A.employees = User_B

我认为我的模型可能是错误的,但本质上我希望能够让用户能够创建餐厅以及被添加为另一家餐厅/他们自己的餐厅的员工。

【问题讨论】:

    标签: ruby-on-rails many-to-many has-and-belongs-to-many


    【解决方案1】:

    你的模型没问题 - 没问题。

    您想要完成的任务,您可以通过以下方式完成:

    restaurant_a = Restaurant.create(restaurant_params)
    # Remember to name it 'restaurant_a', it is convention in Ruby
    user_a.restaurants << restaurant_a
    

    &lt;&lt; 是将左侧事物插入其右侧事物的运算符。因此,在我们的例子中,它会将restaurant_a 插入与user_a 关联的restaurants 列表中,然后您在user_a 上调用save 操作,例如user_a.save

    同样的情况在另一边:

    restaurant_a.employees << user_b
    # According to Ruby convention, you shouldn't start your variable
    # name with an upper case letter, and you should user a convention
    # called 'snake_type' naming convention. So instead of naming
    # your variable like 'firstDifferentUser', name it 'first_different_user'
    # instead.
    restaurant_a.save # To successfully save the record in db
    

    编辑:

    用于创建表单:

    <%= form_for(@restaurant, @employee) do |f| %>
      <%= f.label :email %>
      <%= f.text_field :email %>
    <% end %>
    

    您需要在员工的控制器 new 操作中定义 @restaurant@employee,因为您将为特定餐厅创建新员工。

    【讨论】:

    • 我明白了,谢谢你 Arslan :)。在创建餐厅后设法完成第一部分。如果我在添加员工时卡在协会的另一端,会通知您。
    • 肯定卡住了。你介意告诉我你将如何继续构建一个表单来检索 Rails 4 中的 :email 参数吗?在那之后,我猜我可以按照 User.find_by(email: params[:email]) 的方式做一些事情
    • 您想要用户可以来的表单,输入他的电子邮件,然后按下提交按钮?这就是您希望接收email 参数的方式吗?
    • 因此,假设用户创建了一家餐厅,现在正在管理它。用户单击一个名为 Add Employee 的按钮,它会将他带到路径 /restaurant/:id/employees/new 中的一个表单。这里有一个带有单个输入的表单:电子邮件和一个提交按钮。提交后,您会收到一条提示消息,说明没有找到该电子邮件的用户,或者您被重定向到 restaurant/:id/employees 并查看新添加的用户。 PS:我正在使用 employees_controller 来处理这个。
    猜你喜欢
    • 2013-12-20
    • 2014-01-03
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多