【发布时间】:2014-12-11 01:13:15
【问题描述】:
我正在尝试将设计 gem 实现到我的网络应用程序中 - 用户登录和注册的所有内容都可以正常工作,但是当用户尝试实际留下预测(您唯一需要登录的内容)时,我收到此错误消息:nil:NilClass 的未定义方法 `user='。我似乎无法弄清楚是什么导致了这个问题。有人知道吗?
_login_items.html.erb:
<ul>
<% if user_signed_in? %>
<li>
<%= link_to('Logout', destroy_user_session_path, :method => :delete) %>
</li>
<% else %>
<li>
<%= link_to('Login', new_user_session_path) %>
</li>
<% end %>
<% if user_signed_in? %>
<li>
<%= link_to('Edit registration', edit_user_registration_path) %>
</li>
<% else %>
<li>
<%= link_to('Register', new_user_registration_path) %>
</li>
<% end %>
</ul>
预测模型:
class Prediction < ActiveRecord::Base
belongs_to :student
belongs_to :user
end
用户模型:
class User < ActiveRecord::Base
has_many :predictions
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
预测迁移:
class CreatePredictions < ActiveRecord::Migration
def change
create_table :predictions do |t|
t.string :prediction
t.belongs_to :student, index: true
t.belongs_to :user
t.timestamps
end
end
end
用户迁移:
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.inet :current_sign_in_ip
t.inet :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
预测控制器:
class PredictionsController <ApplicationController
def create
@prediction.user = current_user
Prediction.create(prediction_params)
redirect_to :back
end
def new
@prediction = Prediction.new(student_id: params[:student_id])
end
def destroy
Prediction.find(params[:id]).destroy
redirect_to :back
end
private
def prediction_params
params.require(:prediction).permit(:prediction) #, :student_id
end
end
【问题讨论】:
标签: ruby-on-rails methods devise gem