用户#show中的NameError - Rails

时间:2016-02-27 22:53:16

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

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

用户中的NameError#显示未定义的局部变量或方法`micropost',此行代码以红色突出显示:

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

这是我的代码:

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.html.erb

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

视图/用户/ show.html.erb

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

2 个答案:

答案 0 :(得分:0)

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

你可以通过下一种方式修复它:

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

答案 1 :(得分:0)

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

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