【问题标题】:How to create an association between devise user model and new model in rails?如何在设计用户模型和 Rails 中的新模型之间创建关联?
【发布时间】: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 文件来确认我的数据库是否正常工作。它工作正常。我可以看到 Bookuser 表中的新条目以及 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_pa​​rams)
  • 啊!这次可以了:)你能解释一下吗
  • 我建议阅读关联指南。我已经包含了关于构建的所属参考:guides.rubyonrails.org/…

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 devise


【解决方案1】:

在你的控制器的创建方法中试试这个

图书控制器类

def create
 @book = current_user.books.build(filtered_params)
 if @book.save
   redirect_to action: 'index'
 else
   render 'new'
 end
end

希望这对你有用。

【讨论】:

    【解决方案2】:

    在 books/new.html.erb 中,在 之前添加以下行:

    <%= f.hidden_field :user_id, value: current_user.id %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多