【问题标题】:*Show* view always shows the first pin (item) in the database*Show* 视图始终显示数据库中的第一个引脚(项目)
【发布时间】:2015-07-16 20:01:21
【问题描述】:

我正在开发一个类似 pinterest 的应用程序,最近遇到了一个问题。 当作为登录用户我尝试通过“显示”访问 pin 时,它会在 url 中为我提供正确的 ID 号,例如http://localhost:3000/pins/7 但描述来自数据库中的第一项。

这是我的显示视图代码:

<%= image_tag @pin.image.url %>

<p>
 <strong> Description: </strong>
  <%= @pin.description %>
</p>

<% if @pin.user == current_user %>
<%= link_to 'Edit', edit_pin_path(@pin) %>
<% end %>

<%= link_to 'Back', pins_path %>

另一方面,当我尝试通过 heroku 通过 show 或 edit 访问它时,它以以下消息结尾:

很抱歉,出了点问题。如果您是应用程序所有者,请查看日志以获取更多信息。”

这是我的 github 仓库https://github.com/LeJaques/myfirstapp_new

我将不胜感激!

【问题讨论】:

  • 您能否添加您的控制器代码,将@pin 设置为您的问题。另外,请检查您的日志中的参数。

标签: ruby-on-rails database heroku show


【解决方案1】:

您的问题似乎出在您的PinController 中的set_pin 方法中。

private
  # Use callbacks to share common setup or constraints between actions.
  def set_pin
    @pin = Pin.find_by(params[:id])
  end

当简单地将params[:id] 传递给find_by 时,您会遇到问题。您应该使用

@pin = Pin.find(params[:id])

@pin = Pin.find_by(id: params[:id])

你在后来的 correct_user 方法中奇怪地使用了后者。

与您的问题无关,但在未来,与其链接到您的 github 项目并让我们挖掘代码,不如将相关代码发布到您的问题中。这样做将有助于您在未来获得更快的答案;如果您的set_pin 方法从一开始就在您的问题中,则此问题将在五分钟内(而不是半小时内)得到回答。

【讨论】:

    【解决方案2】:

    看起来您使用 find_by 错误地设置了 @pin

    def set_pin
      @pin = Pin.find_by(params[:id])
    end
    

    尝试将其更改为 Pin.find(params[:id]) 或添加一个字段以通过 Pin.find_by(id: params[:id]) 进行搜索

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      相关资源
      最近更新 更多