【问题标题】:Rails with Devise: Problems with associationsRails with Devise:关联问题
【发布时间】:2013-03-25 18:27:53
【问题描述】:

我制作了新的 Rails 应用程序。只有一个 User 模型(通过 Devise 生成)和一个用脚手架生成的 Post 模型,它是完全新鲜的。在 Post 模型中,我在数据库中有一个名为 user_id 的列。

问题在于 Post 表中的 user_id 始终是 nil(它不会更改为正在发帖的用户的 user_id)。我怀疑这与设计有关,但我不完全确定。有什么建议吗?

user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_many :posts, dependent: :destroy
end

post.rb

class Post < ActiveRecord::Base
  attr_accessible :title, :user_id
  belongs_to :user
end

宝石文件

source 'https://rubygems.org'

gem 'rails', '3.2.13'
gem 'bootstrap-sass', '2.1'
gem 'devise'

group :development do
  gem 'sqlite3', '1.3.5'
end

group :assets do
  gem 'sass-rails',   '3.2.5'
  gem 'coffee-rails', '3.2.2'

  gem 'uglifier', '1.2.3'
end

gem 'jquery-rails', '2.0.2'

group :production do
    gem 'pg', '0.12.2'
end

gem 'will_paginate', '> 3.0'

post_controller(创建)

  def create
    @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

【问题讨论】:

  • 显示你的PostController#create方法
  • 您是否为 user_id 字段分配了任何内容?您可以从 current_user.id 获取当前用户的 id
  • 现在添加了创建方法。我应该如何分配它 - 在创建方法中(如何)?

标签: ruby-on-rails devise associations


【解决方案1】:

我猜user_id 属性没有被设置,因为你没有设置它。 :)

  def create
    @post = Post.new(params[:post])
    @post.user_id = current_user.id # You need to add this line

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

旁注:我建议在post.user_id 上设置一个非空约束,以及(如果您还没有)从post.user_iduser.id 的外键约束。这些限制有助于预防和更轻松地诊断此类问题。

【讨论】:

  • 我虽然用has_manybelongs_to“自动”处理了这个问题。但这不是真的吗?我需要手动写那行吗?
  • has_manybelongs_to 会让你做一些方便的事情,比如user.postspost.user,但是设置属性的唯一方法是在表单中设置它或者在某个地方设置它否则,就像控制器一样。
  • 顺便说一句,您可以在表单中设置帖子的user_id,就像使用隐藏字段一样。不过,我倾向于避免这种情况,因为足够精明的修补匠可以将隐藏字段的 user_id 值更改为其他用户的 id,然后您的帖子将被保存给错误的用户。当然,在这种特殊情况下,这不是一个巨大的安全问题,但一般来说,这可能是一个好习惯。
  • 说真的,我在这个问题上用了一整天。非常感谢杰森!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多