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
查看用户看到类似这样的信息:
团体发送给:
名经理[ “加里”, “安妮”] [ “安妮”]
董事[ “戴夫”]
当我想要的是显示为:
组发送到:
经理加里,安妮
董事戴夫
有人可以帮助我吗?