Model 构建Rails 3.1

Model 构建Rails 3.1,model,ruby-on-rails-3.1,associations,Model,Ruby On Rails 3.1,Associations,每当我创建一个用户并登录时,这个异常就会在重定向上抛出:找不到没有ID的用户 我有很多这样的联想: 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_i

每当我创建一个用户并登录时,这个异常就会在重定向上抛出:
找不到没有ID的用户

我有很多这样的联想:

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
以及User.authenticate方法/sessioncontroller
create
action

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

问题似乎很简单-您将经过身份验证的用户的id存储在会话对象中,但尝试使用
参数[:User\u id]
而不是
会话[:User\u id]

获取用户,看起来参数[:id]为空,但它应该指向某个用户。另外,在准备帖子时,你应该使用标签联想,而不是标签。谢谢,你能解释一下为什么是复数而不是单数吗?是因为它是孩子吗?因为你在
Post
模型中声明了
有很多:tags
,你应该使用
Post.tags
new
create
actions
@Post=@user.Post.tags.build()
的解决方案也是如此吗?一旦你加载了
@user
,您可以使用
@post=@user.posts.build
构建post,然后使用
@post.tags.build
。也许,您应该将这些准备工作转移到
Post
模型中。
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
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