2017-04-26 61 views
0

我想製作一個名爲subject_types的表格,並使用不同的主題(如英語,西班牙語,歷史)填充表格。並將subjects表分配給每個user。我希望用戶能夠通過複選框選擇多個subjects,並且會保存這些特定的並保持檢查。每個用戶可以保存自己的preferences/services。我試圖找出解決這個問題的最佳方法。RAILS:使用複選框和類別爲用戶保存類別/主題表

這裏是它會怎樣看 enter image description here

  • 的方式將用戶編輯它們的設置。我希望能夠獲取這些信息,並稍後使用它來查找僅包含所選主題類型的結果。有沒有教程或類似的參考?

- 我應該製作subject_types模型並填充這些主題還是有更好的方法?

可能的解決方案

  • 我能有一列在我的用戶表中的數組?該數組將是subjects表的ID。我怎樣才能做到這一點??

謝謝

更新時間:

<%= form_for(@user) do |f| %> 
 

 
    
 
<%= f.collection_check_boxes(:writing_type_ids, WritingType.all, :id, :name) %> 
 
    
 
    <%= f.submit 'submit' %> 
 
<% end %>

class WritingType < ActiveRecord::Base 
    has_many :user_writing_types 
    has_many :users, through: :user_writing_types 
end 


class UserWritingType < ApplicationRecord 
    belongs_to :user 
    belongs_to :writing_type 
end 


class User < ActiveRecord::Base 
has_many :user_writing_types 
has_many :writing_types, through: :user_writing_types 
end 

我要遷移的加入

create_table :user_writing_types do |t| 
     t.belongs_to :user, index: true 
     t.belongs_to :writing_type, index: true 
     t.boolean :active, default: false 
     t.timestamps 
    end 

最新更新

即時得到我的最後一個錯誤的!當我點擊提交在該頁上我得到No route matches [PATCH] "https://stackoverflow.com/users/51"

  • deviseedit.html.erb加入這個<%= f.collection_check_boxes(:writing_type_ids, WritingType.all, :id, :name) %>到我的編輯表單。 writing_type名稱填充在複選框上,但沒有任何內容被提交到數據庫的user_writing_type表中。

回答

1

開始通過使用has_many :through associations創建一個多對多的關係與加盟模式:

class User < ApplicationRecord 
    has_many :user_subjects 
    has_many :subjects, through: :user_subjects 
end 

class Subject < ApplicationRecord 
    has_many :user_subjects 
    has_many :users, through: :user_subjects 
end 

# this is the join model 
class UserSubject < ApplicationRecord 
    belongs_to :user 
    belongs_to :subject 
end 

然後,您可以創建一個複選框對象添加到用戶與collection_checkboxes

<%= form_for(@user) do |f| %> 
    <%= f.collection_checkboxes(:subject_ids, Subject.all, :id, :name) %> 
    # ... 
<% end %> 

我可以在我的用戶表的列中有一個數組嗎?該數組將是主題表的ID號爲 。我怎樣才能做到這一點??

你不知道。

儘管Postgres例如允許您創建數組類型列 它不是一個好的解決方案,因爲這不是關聯關係如何在ActiveRecord中工作。

它也是一個糟糕的關係數據庫設計作爲其凌亂編寫查詢與聯接雖然數組列,它不會讓你實施參照完整性外鍵或具有良好的性能指標。

+0

即時得到我的錯誤了!當我點擊提交我得到'不路由匹配[PATCH]「/用戶/ 51」',我有一個想法,如何將其路由在routes.rb中,但我想最好的辦法,到目前爲止,你已經使我對正確的路徑。 –

+0

將'resources:users'添加到'routes.rb'。你似乎已經完全誤解了 - 你可以通過更新父記錄(用戶)而不是通過向WriteTypesController發送請求來創建關聯。 (你的命名過​​於複雜和奇怪)。 – max

+0

好吧,用戶記錄獲取數據,它存儲在哪裏?我使用設計爲我的用戶,所以在路線我有devise_for與路徑名稱。我在想加入'collection_check_boxes'我'設計/註冊/ edit'頁形式:'<%=的form_for(資源,如:RESOURCE_NAME,網址:registration_path(RESOURCE_NAME),HTML:{方法:放,多:true},:validate => true)do | f | %>'。當我更新時,在編輯頁面中它不保存。當我回去時,複選框仍未被選中。 –