0
无论何时我创建一个用户并登录,这个异常都会引发重定向:Couldn't find User without an ID
。构建关联Rails 3.1
我有一个has_many
协会,像这样:
class Post < ActiveRecord::Base
has_many :tags
belongs_to :user
attr_accessible :title, :description, :content, :tags_attributes
accepts_nested_attributes_for :tags, allow_destroy: true, reject_if: lambda {|attrs| attrs.all? {|key, value| value.blank?}}
end
依次为:
class User < ActiveRecord::Base
has_many :posts
attr_accessible :codename, :password, :password_confirmation
end
还有第三种模式“标签”具有belongs_to post
但这似乎并没有被引起问题。还有一个SessionsController与new
,create
和destroy
行动(代码如下)。
的find_user
方法仅在新的运行,并在PostsController
before_filter :find_user
def find_user
@user = User.find(params[:user_id])
end
def new
@post = @user.posts.build(tags: Tag.new)
respond_to do |format|
format.html
end
end
def create
@post = @user.posts.build(params[:post])
@tags = @post.tags.build(params[:tags])
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
else
format.html { render action: :new }
end
end
end
和User.authenticate方法采取/ SessionsController create
行动
def self.authenticate(codename, password)
user = User.find_by_codename(codename)
unless user && user.authenticate(password)
raise "You are not who you say you are."
end
user
end
def create
session[:user_id] = User.authenticate(params[:codename], params[:password]).id
redirect_to action: session[:intended_action], controller: session[:intended_controller], success: "You're In!"
end
看起来像params [:id]是空的,但它应该指向某个用户。另外,准备帖子时,您应该使用标签关联,而不是标签。 – taro 2012-01-02 16:59:40
谢谢,你能解释为什么复数而不是单数?是因为它是小孩吗? – rhodee 2012-01-02 17:21:21
因为你在'Post'模型中声明'has_many:tags',所以你应该使用'post.tags'。 – taro 2012-01-02 18:04:52