1
我已經按照這裏的教程:http://www.sitepoint.com/messaging-rails-mailboxer/來實現郵箱gem進入我的應用程序及其應有的工作。將郵箱對話限制在特定用戶之間
- 如果當前用戶是學生(枚舉:1),它可以只發送短信到只有一個用戶它配對但是實施現在我需要以某種方式限制的方式,用戶之間的對話後,在配對錶中。
- 如果當前用戶是主管(枚舉:2),它只能將消息發送給在配對錶中配對的學生用戶。
我想我需要對messages_helper模塊進行更改,但我不知道該做什麼。
模型User.rb
class User < ActiveRecord::Base
enum role: [:student, :supervisor, :admin]
after_initialize :set_default_role, :if => :new_record?
has_many :students, class_name: "User",
foreign_key: "supervisor_id"
belongs_to :supervisor, class_name: "User"
has_and_belongs_to_many :pairings
def set_default_role
self.role ||= :student
end
def mailboxer_email(object)
email
end
acts_as_messageable
end
模型Pairing.rb
class Pairing < ActiveRecord::Base
has_and_belongs_to_many :supervisor, class_name: 'User'
belongs_to :student, class_name: 'User'
end
架構這些模型中的(不相關的領域中省略)
create_table "pairings", force: :cascade do |t|
t.integer "supervisor_id"
t.integer "student_id"
t.string "project_title"
end
add_index "pairings", ["student_id"], name: "index_pairings_on_student_id", unique: true
add_index "pairings", ["supervisor_id"], name: "index_pairings_on_supervisor_id"
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email", default: "", null: false
t.integer "role"
end
messages_controller.rb
class MessagesController < ApplicationController
before_action :authenticate_user!
def new
@chosen_recipient = User.find_by(id: params[:to].to_i) if params[:to]
end
def create
recipients = User.where(id: params['recipients'])
conversation = current_user.send_message(recipients, params[:message][:body], params[:message][:subject]).conversation
flash[:success] = "Message has been sent!"
redirect_to conversation_path(conversation)
end
end
個
messages_helper.rb
module MessagesHelper
def recipients_options(chosen_recipient = nil)
s = ''
User.all.each do |user|
s << "<option value='#{user.id}' #{'selected' if user == chosen_recipient}>#{user.name}</option>"
end
s.html_safe
end
end
new.html.erb(查看用於發送消息)
<% header "Start Conversation" %>
<%= form_tag messages_path, method: :post do %>
<div class="form-group">
<%= label_tag 'message[subject]', 'Subject' %>
<%= text_field_tag 'message[subject]', nil, class: 'form-control', required: true %>
</div>
<div class="form-group">
<%= label_tag 'message[body]', 'Message' %>
<%= text_area_tag 'message[body]', nil, cols: 3, class: 'form-control', required: true %>
</div>
<div class="form-group">
<%= label_tag 'recipients', 'Choose recipients' %>
<%= select_tag 'recipients', recipients_options(@chosen_recipient), multiple: true, class: 'form-control chosen-it' %>
</div>
<%= submit_tag 'Send', class: 'btn btn-primary' %>
<% end %>