【问题标题】:NameError in Users#show - Rails用户#show中的NameError - Rails
【发布时间】:2016-02-27 22:53:15
【问题描述】:

我正在关注 Michael Hurtl 的 Rails 教程,在第 11 章中,当我想查看用户的个人资料页面时,我收到此错误:

NameError in Users#show undefined local variable or method `micropost' 并且这行代码以红色突出显示:

这是我的代码:

microposts_controller.rb

class MicropostsController < ApplicationController
        before_action :authenticate_user! , only: [:create,:destroy]

    def create
        @micropost = current_user.microposts.build(micropost_params)

        if @micropost.save
            flash[:success] = "Micropost created"
            redirect_to root_url
        else
            render 'pages/home'
        end
    end

    def destroy
    end

    private

    def micropost_params
        params.require(:micropost).permit(:content)
    end
end

users_controller.rb

class UsersController < ApplicationController
    before_action :authenticate_user! , only: [:edit,:update,:destroy]

    def index
        @users = User.all
    end

    def show
        @user = User.find(params[:id])
        @microposts = @user.microposts
    end

end

microposts/_microposts.html.erb

<%= link_to micropost.user.name , micropost.user%>

views/users/show.html.erb

  <h2>User Profile</h2>
    <% if @user.microposts.any? %>
    <h3>Microposts</h3>
    <%= @user.microposts.count%>
    <%= render 'microposts/microposts' %>
    <%end%>

【问题讨论】:

  • 您没有将micropost 变量设置为部分,添加到您的问题中,如何将部分添加到视图中

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2


【解决方案1】:

您似乎没有将micropost 变量设置为部分

您可以通过以下方式修复它:

<%= render partial: 'microposts/_microposts', collection: @microposts %>

【讨论】:

    【解决方案2】:

    你的部分应该有这样的东西:

    <% @microposts.each do |micropost| %>
    <%= link_to micropost.user.name , micropost.user%>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多