【发布时间】:2016-03-25 16:15:42
【问题描述】:
简而言之,我的视图中有一些 if/else 逻辑,我认为它们作为控制器方法或帮助器会更有效。也就是说,我不确定将其转化为方法的最佳方式是什么,或者放置它的最佳位置。
我正在我的 Rails 应用程序中构建一个用户消息传递系统。在我的应用程序中,个人资料有许多对话(两个个人资料之间),其中包含许多消息。我正在尝试构建基本上就像收件箱一样的对话索引。作为一名 Rails 初学者,我不太确定将 if/else 部分移出视图的最有效/最佳方式是什么,因为它在 .each 循环中运行。现在我的观点是这样的:
<% @conversations.each do |conversation| %>
<% if conversation.sender_id == current_user.profile.id %>
<% recipient = Profile.find(conversation.recipient_id) %>
<% else %>
<% recipient = Profile.find(conversation.sender_id) %>
<% end %>
<%= link_to recipient.first_name, conversation_messages_path(conversation)%>
供参考我的对话控制器索引操作:
def index
@profiles = Profile.all
@conversations = Conversation.involved(current_user.profile.id)
end
还有我的对话模式
class Conversation < ActiveRecord::Base
belongs_to :sender, :foreign_key => :sender_id, class_name: 'Profile'
belongs_to :recipient, :foreign_key => :recipient_id, class_name: 'Profile'
has_many :messages, dependent: :destroy
accepts_nested_attributes_for :messages
validates_uniqueness_of :sender_id, :scope => :recipient_id
scope :between, -> (sender_id,recipient_id) do
where("(conversations.sender_id = ? AND conversations.recipient_id =?) OR (conversations.sender_id = ? AND conversations.recipient_id =?)", sender_id,recipient_id, recipient_id, sender_id)
end
scope :involved, -> (user) do
where("(conversations.sender_id = ? OR conversations.recipient_id =?)", user, user)
end
end
这是我的第一个 stackoverflow 问题,所以如果我没有遵循此问题的任何最佳做法,请告诉我!
【问题讨论】:
标签: ruby-on-rails views messaging