Post.Username 不会在 haml 中显示?

Post.Username wont display inside haml?

好吧,我想这可能是一个非常直接的问题。我似乎破坏了我的应用程序的一项功能,该功能显示提交 post 的人的用户名(在我的例子中是 'pin')。

这一切都发生在我将用户名添加到数据库(设计)的时候,因为以前我只显示电子邮件地址,我觉得这不是我真正想要的。

Tl;dr: = pin.user.username (app/views/pins/index.html.haml) 不不显示提交 post 的人的用户名。但是它将显示带有 pin.user.email.

的电子邮件

这是我的 PinsController(我的 Pin 是设计中的 Post)

class PinsController < ApplicationController
before_action :find_pin, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
before_action :authenticate_user!, except: [:index, :show]

attr_accessor :username

def index
    @pins = Pin.all.order("created_at DESC")
end

def show
end

def new
    @pin = current_user.pins.build
end

def create
    @pin = current_user.pins.build(pin_params)

    if @pin.save
        redirect_to @pin, notice: "Fit was successfully created"
    else
        render 'new'
    end
end

def edit
end

def update
    if @pin.update(pin_params)
        redirect_to @pin, notice: "Fit was successfully updated"
    else
        render 'edit'
    end
end

def destroy
    @pin.destroy
    redirect_to root_path
end

def upvote
    @pin.upvote_by current_user
    redirect_to :back
end

private

def pin_params
    params.require(:pin).permit(:title, :description, :image)
end

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

end

这是我的索引。html.haml

#pins.transitions-enabled
- @pins.each do |pin|
    .box.panel.panel-default
        = link_to (image_tag pin.image.url), pin
        %h2= link_to pin.title, pin
        %p.user
            Submitted by
            = pin.user.username

我的架构为用户显示了这个

  add_index "pins", ["user_id"], name: "index_pins_on_user_id"

create_table "users", force: true do |t|
t.string   "email",                  default: "", null: false
t.string   "encrypted_password",     default: "", null: false
t.string   "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer  "sign_in_count",          default: 0,  null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string   "current_sign_in_ip"
t.string   "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string   "username"
end

我已附上我的 git 以防您需要一些具体细节 https://github.com/thgilartlU/MyFitIdentity

你的问题不是问题,而是你试图显示的用户名似乎是空的。您的 haml 结构看起来很好。 正如您在 pin_params 中提到的 username 是不允许的,因此请确保允许并将其保存到数据库中。比你的 haml 应该工作。

删除

attr_accessor :username

def username=(username)
  @username = username
end

从您的 user.rb 模型文件中,它弄乱了 ActiveRecord