我一直在尝试为我的网站构建一个消息系统,该系统使用设备进行身份验证。它所需的功能是能够向一个或多个收件人发送消息(最好使用也列出用户的 list 表单)。经过一段时间的搜索,我发现了一些很棒的东西,例如 Mailer,但我并不需要它的所有功能,并且想构建自己的系统以供学习(仍然是 Rails 的新手)。
我遵循了这个古老的教程( http://web.archive.org/web/20100823114059/http://www.novawave.net/public/rails_messaging_tutorial.html )。我意识到这是一个非常古老的教程,但它是我能找到的唯一一个与我想要实现的目标相匹配的教程。
我已经完全按照教程进行操作,甚至在我的代码不起作用后复制并粘贴了教程中的代码。
尝试访问 http://localhost:3000/mailbox 时我在 MailboxController#index 中收到 NoMethodError
undefined method `messages' for nil:NilClass
app/controllers/mailbox_controller.rb:12:in `show'
app/controllers/mailbox_controller.rb:6:in `index'
我也引用过这个问题Rails 3: undefined method messages for Folder它和我有同样的错误,但这个话题似乎没有任何进展。
mailbox_controller.rb
class MailboxController < ApplicationController
def index
@folder = current_user.inbox
show
render :action => "show"
end
def show
@folder ||= current_user.folders.find_by(params[:id])
@messages = @folder.messages :include => :message, :order => "messages.created_at DESC"
end
end
模型/文件夹.rb
class Folder < ActiveRecord::Base
acts_as_tree
belongs_to :user
has_many :messages, :class_name => "MessageCopy"
end
对此的任何帮助都会很棒,如果您需要更多信息,请告诉我并将发布它。
最佳答案
我最终通过一些修改弄清楚了消息系统。我想发布我的整个解决方案,因为它给我带来了困难,但可能对其他人有用。我保持它非常简单,并且没有包含最初给我带来问题的文件夹模型,但它仍然可以正常工作。
这是我的关联
模型/消息.rb
attr_reader :user_tokens
belongs_to :sender, :class_name => 'User'
has_many :recipients
has_many :users, :through => :recipients
def user_tokens=(ids)
self.user_ids = ids
end
模型/recipient.rb
belongs_to :message
belongs_to :user
模型/用户.rb
has_many :messages, :foreign_key => :sender_id
这是我的消息 Controller
messages_controller.rb
def new
@message = Message.new
@user = current_user.following
@users = User.all
# @friends = User.pluck(:name, :id).sort
end
def create
@message = current_user.messages.build(message_params)
if @message.save
flash[:success] = "Message Sent!"
redirect_to messages_path
else
flash[:notice] = "Oops!"
render 'new'
end
end
def index
@user = User.find(current_user)
@messages = Recipient.where(:user_id => @user).order("created_at DESC")
end
private
def message_params
params.require(:message).permit(:body, :sender_id, user_tokens: [])
end
我的观点
_form.html.erb
</div>
<!-- displays the current users frinds their following -->
<%= f.select :user_tokens, @user.collect {|x| [x.name, x.id]}, {}, :multiple => true, class: "form-control" %>
<br>
<div class="modal-footer">
<%= f.button :submit, class: "btn btn-primary" %>
</div>
架构
消息表
t.text "body"
t.integer "sender_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "body_html"
收件人表
t.integer "message_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
我希望这会有所帮助。
关于ruby-on-rails - 在 Rails 4 中从头开始构建具有多个收件人的消息传递系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28034565/