Ruby on rails 如何获取数据库,然后在视图中显示结果?
我是RubyonRails的新手。这里我有一个叫做“比桑”的模型。我还有一个叫做“会话”的控制器。Pesans有3个属性(接收者、发送者和文本) 用户可以编写新消息。撰写消息时,会话控制器中有一个方法:Ruby on rails 如何获取数据库,然后在视图中显示结果?,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我是RubyonRails的新手。这里我有一个叫做“比桑”的模型。我还有一个叫做“会话”的控制器。Pesans有3个属性(接收者、发送者和文本) 用户可以编写新消息。撰写消息时,会话控制器中有一个方法: def createPesan user = Users.find_by_username(params[:receiver]) if user pesan = Pesans.new pesan.receiver = params[:receive
def createPesan
user = Users.find_by_username(params[:receiver])
if user
pesan = Pesans.new
pesan.receiver = params[:receiver]
user = Users.find(session[:user_id])
pesan.sender = user.username
pesan.text = params[:text]
pesan.save
render 'message'
else
render 'MsgError'
end
end
它工作得非常好(我还使用rails命令提示符查看了数据库,新消息真的保存了下来)。以下是我在会话控制器中获取消息的方法:
def current_inbox
@current_inbox ||= current_user && Pesans.where(["receiver = ?", current_user.username]).select("sender, text").all
end
我的视图中有代码显示与当前用户(收件箱web中的登录用户)对应的PESAN:
收件箱为空
但它始终显示“收件箱为空”,尽管有对应用户的消息(current_user.username)。我哪里出错了?通过更改视图的名称解决了这个问题。非常感谢。虽然我还是不明白为什么-_- 虽然我还是不明白为什么 让我解释一下 -- 以下是我在会话控制器中获取消息的方法:
def current_inbox
@current_inbox ||= current_user && Pesans.where(["receiver = ?", current_user.username]).select("sender, text").all
end
这个叫什么名字
我打赌您已将视图
名称更改为当前收件箱.html.erb
-如果是这种情况,它将确认您出现问题的原因-控制器中将不会调用您的当前收件箱
方法
您要做的是将current\u收件箱
放入(app/helpers/***\u helper.rb
)-这将使您的current\u收件箱
helper在视图中可用,允许您像局部变量一样调用它:
#app/helpers/application_helper.rb
Class ApplicationHelper
def current_inbox
current_user && Pesans.where(["receiver = ?", current_user.username]).select("sender, text").all
end
end
这样做的原因其实很简单
当您运行应用程序(发送请求)时,它基本上会运行特定的控制器操作(方法)。这将意味着控制器中的任何相邻方法(在您的情况下,current\u inbox
)都不会被调用-这只是您请求的操作/方法
解决方法是使用回调,例如:
#app/controllers/your_controller.rb
类YourController
如果你是这样(我没有你应用程序的代码)-你对视图的重命名将基本上允许你运行所需的操作,而不是正确调用它
--
型号
你提到你给你的模特打电话了peans
如果您希望在将来更新Rails时打破Rails约定(从而导致)问题,那么这很好
Rails'和它们的表是复数形式。除此之外的任何东西都会打破惯例,并使您面临升级问题只是好奇,您使用的是复数型号名称吗?解释得很好。
#app/helpers/application_helper.rb
Class ApplicationHelper
def current_inbox
current_user && Pesans.where(["receiver = ?", current_user.username]).select("sender, text").all
end
end
#app/controllers/your_controller.rb
Class YourController < ApplicationController
before_action :current_inbox
private
def current_inbox
#... logic here
end
end