2015-07-10 36 views
0

我在自學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參數,檢查是否存在具有輸入電子郵件的用戶,並將關係添加到employees表中。

我希望能夠做這樣的事情:

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

我覺得我的模型可能是錯誤的,但本質上我希望能夠有用戶創建一個餐廳的能力以及作爲另一家餐館/他們自己的餐館的僱員加入。

回答

1

你的模型沒問題 - 沒有問題。

你所要完成的,你可以完成,通過以下:

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

<<是插入左側的東西放在了右手的事操作。因此在我們的情況下,它會將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 %> 

而且你需要定義你的員工的@restaurant@employee控制器new行動,因爲你要爲特定的r創建一個新員工estaurant。

+0

我明白了,謝謝阿爾斯蘭:)。管理在創建餐廳時完成第一部分。如果在添加員工時遇到協會的另一端,請告知您。 –

+0

肯定卡住了。你介意告訴我你將如何繼續並建立一個表單來檢索Rails 4中的email參數嗎?之後,我猜我可以按照User.find_by(email:params [:email])的方式做一些事情。 –

+0

你想要用戶可以來的表單,把他的電子郵件,然後按提交按鈕?這是你想如何接收'電子郵件'參數? –