gpt4 book ai didi

ruby-on-rails - 如何获取数据库,然后在 View 中显示结果?

转载 作者:太空宇宙 更新时间:2023-11-03 16:01:21 25 4
gpt4 key购买 nike

我是 Ruby on Rails 的新手。在这里,我有一个名为“Pesans”的模型。我还有一个名为“ session ”的 Controller 。 Pesans 有 3 个属性(接收者、发送者和文本)

用户可以撰写新消息。撰写消息时,我在 session Controller 中有方法:

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 命令提示符查看了数据库,新消息确实被保存了)。这是我在 session Controller 中获取消息的方法:

def current_inbox
@current_inbox ||= current_user && Pesans.where(["receiver = ?", current_user.username]).select("sender, text").all
end

在我看来,我有代码显示与 current_user(收件箱网络中的登录用户)相对应的 Pesans:

    <% if @current_inbox.blank? %>
Inbox Empty
<% else %>
<% for pesan in @current_inbox %>
<%= pesan.sender %> <br>
<%= pesan.text %> <br>
<% end %>
<% end %>

但它一直显示“收件箱为空”,尽管相应用户 (current_user.username) 有一条消息。我哪里出错了?

最佳答案

Although I still don't get It why

我来解释一下

--

Here is my method in sessions controller to fetch the message:

def current_inbox
@current_inbox ||= current_user && Pesans.where(["receiver = ?", current_user.username]).select("sender, text").all
end

这是在哪里调用的?

我打赌你将你的 view 名称更改为 current_inbox.html.erb - 如果是这样,它证实了你遇到问题的原因 - 你的 current_inbox 方法不会在你的 Controller 中被调用

您要做的是将 current_inbox 放入 helper 中(app/helpers/***_helper.rb) - 这将使您的 current_inbox 助手在您的 View 中可用,允许您像局部变量一样调用它:

#app/helpers/application_helper.rb
Class ApplicationHelper
def current_inbox
current_user && Pesans.where(["receiver = ?", current_user.username]).select("sender, text").all
end
end

这样做的原因其实很简单

当您运行您的应用程序(向其发送请求)时,它基本上会运行一个特定的 Controller 操作(方法)。这意味着 Controller 中的任何相邻方法(在您的情况下 current_inbox)都不会被调用 - 它是您请求的操作/方法

解决方法是使用回调,例如 before_action :

#app/controllers/your_controller.rb
Class YourController < ApplicationController
before_action :current_inbox

private

def current_inbox
#... logic here
end
end

如果您是这种情况(我没有您的应用程序的代码)- 您对 view 的重命名基本上允许您运行所需的操作,而不是调用它适本地

--

型号

你提到你称你的模型为 Peasans

如果您希望在将来更新 Rails 时打破 Rails 约定(从而导致)问题,那很好

Rails' models are meant to be singular , 他们的表格是复数的。除此以外的任何事情都会打破惯例,并让您敞开心扉去解决升级问题

关于ruby-on-rails - 如何获取数据库,然后在 View 中显示结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24226541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com