0

在我的RoR應用程序中,我試圖在視圖上顯示關聯表中的信息。Ruby on Rails:使用函數從模型中檢索數據

我有一個數據表像這樣:

Email 
id  subject 
1  This week's work 
2  Presentation 
3  Spreadsheets 

Recipients 
email_id  group_id 
1    2 
2    2 
3    1 
1    3 

Groups 
id  name 
1   Managers 
2   Employees 
3   Directors 

Contactgroups 
group_id  contact_id 
1    1 
2    1 
1    3 
3    2 

Contacts 
id   email 
1   Gary 
2   Dave 
3   Annie 

我所試圖做的是顯示已發送的電子郵件,以及每個組成員組的列表。例如,電子郵件1「本週的工作」已發送給小組1「經理」和3「董事」,「經理」小組由聯繫人加里和安妮和「董事」小組組成,聯繫人「戴夫」。因此,在show.html.erb頁面上,我想要顯示電子郵件的詳細信息以及發送給它的組和每個聯繫人。

爲了做到這一點,show.html.erb網頁上我的代碼:

<p> 
    <strong>Groups Sent To:</strong></br> 
    <% @recipients.each do |recipient| %> 
     <%= recipient.group.name %> 
     <% for i in 0..count_group_members(recipient.group.id)-1 do %> 
      <%= group_member_name(recipient.group.id, i) %> 
     <% end %></br> 
    <% end %> 
</p> 

在我emails_controller我的代碼:

class EmailsController < ApplicationController 
    helper_method :count_group_members, :group_member_name 
    def index 
     @useraccounts = Useraccount.where(user_id: session[:user_id]) 
     accountsarray = [0] 
     @useraccounts.each do |f| 
      accountsarray << f.account_id 
     end 
     # find all emails where the account_id is in the array - and so belongs to the user 
     @emails = Email.where(account_id: [accountsarray]) 
    end 
    def show 
     @email = Email.find(params[:id]) 
     @account = Account.find_by_id(@email.account_id) 
     @recipients = Recipient.where(email_id: @email.id) 
    end 
    def new 
     @email = Email.new 
     @email.recipients.build 
     @useraccounts = Useraccount.where(user_id: session[:user_id]) 
    end 
    def edit 
     @email = Email.find(params[:id]) 
     @useraccounts = Useraccount.where(user_id: session[:user_id]) 
    end 
    def create 
     @email = Email.new(email_params) 
     if @email.save 
      redirect_to @email 
     else 
      render 'new' 
     end 
    end 
    def update 
     @email = Email.find(params[:id]) 
     if @email.update(email_params) 
      redirect_to @email 
     else 
      render 'edit' 
     end 
    end 
    def destroy 
     @email = Email.find(params[:id]) 
     @email.destroy 
     redirect_to emails_path 
    end 
    def count_group_members(group) 
     Contactgroup.where(group_id: group).count 
    end 
    def group_member_name(group, i) 
     contact = Contactgroup.where(group_id: group).offset(i).pluck(:contact_id) 
     Contact.where(id: contact).pluck(:firstname) 
    end 
    private 
    def email_params 
     params.require(:email).permit(:subject, :message, :account_id, { contact_ids: [] }, { group_ids: [] }) 
    end 
end 

這樣做的問題是,在show.html.erb查看用戶看到類似這樣的信息:

團體發送給:

經理[ 「加里」, 「安妮」] [ 「安妮」]

董事[ 「戴夫」]

當我想要的是顯示爲:

組發送到:

經理加里,安妮

董事戴夫

有人可以幫助我嗎?

回答

0

所有我需要做的是改變以下線在我的控制器:

def group_member_name(group, i) 
    contact = Contactgroup.where(group_id: group).offset(i).pluck(:contact_id) 
    Contact.find_by_id(contact).firstname 
end