我有一個用戶和鏈接MVC。我將它們列在下面。基本上,當我創建一個新鏈接時,我希望它與我的用戶綁定,然後在我的顯示頁面上顯示帶有引號的用戶電子郵件,但是當我進行身份驗證時,我仍然得到一個零值用戶:用戶和鏈接關聯困難
- 用戶和鏈路ASSOCATION
- 允許在我的強烈參數
:user_id
- 已要求用戶一個的before_filter作出新的請求
- 當記錄有USER_ID我的鏈接模式
如果您看看我的show.html.erb和行<%= @link.user.try(:email) %>
,這是發佈該鏈接的用戶電子郵件應該出現的位置,但它們都以零值表示。
我現在有點迷路,爲什麼我不能得到這個工作,任何幫助將非常感激!
型號:
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
謝謝你的回答,協會現在正常工作。出於我自己的好奇心,你爲什麼認爲link_params沒有設置用戶?至於你最後的評論,我應該運行一個遷移改變user_id爲null:我的鏈接表中的false? – Jbur43
因爲你的表單很可能沒有user_id字段(或者它是空白的)。我會編寫一個遷移來更改user_id的nullness,但這取決於您(並且您需要刪除任何具有空user_id的行) –
感謝您花時間解釋這一點,我非常感謝。 – Jbur43