在我的RoR应用程序中,我试图在视图上显示关联表的信息。
我的表格包含以下数据:
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"董事","经理"小组由联系人Gary和Annie以及" Directors"小组由联系人" Dave"组成。因此,在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
视图中,用户可以看到如下信息:
发送给的群组:
经理[&#34; Gary&#34;,&#34; Annie&#34;] [&#34; Annie&#34;]
导演[&#34; Dave&#34;]
当我想要显示为:
发送给的群组:
经理Gary,Annie
导演戴夫
有人可以帮帮我吗?
答案 0 :(得分: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