【发布时间】:2015-12-27 14:36:56
【问题描述】:
我有一个用户和链接 MVC。我在下面列出了它们。基本上,当我创建一个新链接时,我希望它与我的用户相关联,然后在我的显示页面上显示带有报价的用户电子邮件,但是当我进行身份验证时,我继续为用户获得 nil 值,即使我有:
- 用户和链接关联
- 在我的强参数中允许
:user_id - 有一个 before_filter 要求用户在发出新请求时登录
- 在我的链接架构中有一个 user_id
如果您查看我的 show.html.erb 和 <%= @link.user.try(:email) %> 行,这应该是发布链接的用户电子邮件的位置,但它们都显示为 nil 值。
我现在有点迷茫,为什么我不能让它工作,任何帮助将不胜感激!
型号:
class User < ActiveRecord::Base
has_many :links
acts_as_voter
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
class Link < ActiveRecord::Base
belongs_to :user
acts_as_votable
attr_accessor :avatar
mount_uploader :avatar, AvatarUploader
end
控制器:
class LinksController < ApplicationController
before_filter :authenticate_user!, except: [:index, :show]
def index
@links = Link.all
end
def show
@link = Link.find(params[:id])
end
def new
@link = Link.new
end
def edit
end
def create
@link = Link.new(link_params)
if @link.save
redirect_to root_path
else
render 'new'
end
end
private
def link_params
params.require(:link).permit(:title, :url, :avatar, :user_id)
end
end
show.html.erb:
<p id="notice"><%= notice %></p>
<p>
<strong>Author:</strong>
<%= @link.title %>
</p>
<p>
<strong>Quote:</strong>
<%= @link.url %>
</p>
<small class="author">Submitted <%= time_ago_in_words(@link.created_at) %> ago by <%= @link.user.try(:email) %></small>
架构:
create_table "links", force: :cascade do |t|
t.string "title"
t.string "url"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "cached_votes_total", default: 0
t.integer "cached_votes_score", default: 0
t.integer "cached_votes_up", default: 0
t.integer "cached_votes_down", default: 0
t.string "avatar"
end
create_table "users", force: :cascade 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", null: false
t.datetime "updated_at", null: false
end
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4 associations schema