2015-10-19 27 views
0

我很掙扎,當涉及到一個聯合表,這也是多態的,有很多。無法使它屬於的模型也是一個可以has_many

它的設置方式是問題屬於公司。問題可以通過question_participants(多態/聯合)屬於用戶,組或公司。

現在我可以保存用戶和組,但不能保存公司,當他們選擇。我認爲這與它作爲所有者的混淆有關。

# ask question 
class QuestionsController < ApplicationController 


    def new 
    @question = current_user.company.questions.new 
    end 

    private 

    def question_params 
    params.require(:question).permit(:name, :optional, 
            user_ids: [], group_ids: []) 
    end 


# company users belong to 
class Company < ActiveRecord::Base  
    has_many :questions 
end 


# questions created by admin 
class Question < ActiveRecord::Base 
    belongs_to :company 
    has_many :question_participants 
    has_many :answers 
    has_many :users, through: :question_participants, 
        source: :questionable, source_type: 'User' 
    has_many :groups, through: :question_participants, 
        source: :questionable, source_type: 'Group' 
    has_many :companies, through: :question_participants, 
         source: :questionable, source_type: 'Company' 
end 

和表單字段:

<%= form_for @question do |f| %> 

    <%= f.label :group_ids %> 
    <%= f.collection_select :group_ids, current_user.company.groups.order(:name), :id, :name, {}, 
     { multiple: true } %> 

    <%= f.label :user_ids %> 
    <%= f.collection_select :user_ids, current_user.company.users.order(:first_name), :id, :first_name, {}, 
    { multiple: true } %> 

    <%= f.label :name %> 
    <%= f.text_field :name, class: "form-control" %> 


    <%= f.submit class: "btn btn-success" %> 

<% end %> 

回答

0

如果問題僅僅是公司正顯示出了兩次關於這一問題的類中的字段,只是改變的has_many線的問題類的底部到:

​​

如果這樣的作品,太棒了!否則....

 

我不知道了很多關於多態性,但是從我所知道的,這就是我想將工作:

用戶,組和公司應該有這條線:

has_many :question_participants, as: questionable 

問題應該使用範圍而不是你有三條線。試試這個:

has_many :questionable, through: :question_participants 

一旦你得到了:作爲可疑問題上的一個字段,那麼你可以讓範圍

scope :questionable_users, -> { where(questionable_type: :User) } 
scope :questionable_groups, -> { where(questionable_type: :Group) } 
scope :questionable_companies, -> { where(questionable_type: :Company) } 

我把questionable_每個範圍之前只是使本公司的關聯不會抱怨。

我忘記了如何將範圍與belongs_to進行比較,但它有可能會遺漏一些您想要的功能。

相關問題