设计的Rails:关联问题

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

问题是Post表中的user_id始终为nil (它不会更改为发布的用户的user_id )。 我怀疑这与Devise有关,但我不完全确定。 关于该怎么做的任何建议?

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 

的Gemfile

 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 

我猜测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的外键约束。 这些限制有助于预防和更容易地诊断这些类型的问题。