【发布时间】:2015-06-29 02:37:34
【问题描述】:
我可以在我的应用程序中轻松地执行 singnin 和 singup 过程,但我无法理解如何在我的新模型中传递 user_id。成功集成设计后,我按照以下步骤操作:
以书名生成新模型
rails generate model books name:string users:references
它在models 文件夹中生成book 类以及migration 类。
模型类
class Book < ActiveRecord::Base
belongs_to :user
end
迁移类
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.string :name
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
现在,我添加
has_many :books, :dependent => :destroy
在user 模型类中建立正确的one to many 关联。
创建这些类后,我运行rake db:migrate,它在项目中创建了一个新模式。创建模式后,我写了seed 文件来确认我的数据库是否正常工作。它工作正常。我可以看到 Book 和 user 表中的新条目以及 Book 表中的 user_id。
路由类
sampleApplicationUI::Application.routes.draw do
devise_for :users
resources :books, except: [:edit]
end
现在,我添加了一个book_controller 类,代码如下:
图书控制器类
class BooksController < ApplicationController
before_action :authenticate_user!
def index
@book = Book.all
end
def new
@book = Book.new
end
def create
@book = Book.new(filtered_params)
if @book.save
redirect_to action: 'index'
else
render 'new'
end
end
private
def filtered_params
params.require(:book).permit(:name, :user_id)
end
....
books/new.html.erb
<%= form_for @book, as: :book, url: book_path do |f| %>
<div class="form-group">
<%= f.label :Name %>
<div class="row">
<div class="col-sm-2">
<%= f.text_field :name, class: 'form-control' %>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<%= f.submit 'Submit', class: 'btn btn-primary' %>
</div>
</div>
我关注了一些博客,他们提到在 book_controller 类中进行以下更改以访问 user_id 并保存到 book 表中:
图书控制器类的变化
def new
@book = Book.new(user: current_user)
end
但在这里我得到No variable defined current_user :(
请让我知道我在这里做错了什么以及如何在book controller 类中访问user.user_id。
感谢您的宝贵时间!
【问题讨论】:
-
您是否已将 :user_id 添加到您的强参数中?
-
尝试将您的新操作更改为@book = current_user.books.build
-
在您的创建操作中将其更改为:@book = current_user.books.build(filtered_params)
-
啊!这次可以了:)你能解释一下吗
-
我建议阅读关联指南。我已经包含了关于构建的所属参考:guides.rubyonrails.org/…
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 devise