嵌套表单验证轨道3.2



我在同一个视图中有一个作业和用户(设计)表单。当我试图在用户字段中出现错误的情况下提交时,它会给我一个包含验证消息的异常页面。在作业字段中提交错误效果良好!

job_controller.rb
def new
  @job = Job.new
  if !current_user
    @job.user = User.new
  end
  respond_to do |format|
    format.html # new.html.erb
  end
end
  def create
    @types = Type.all
    @categories = Category.all
    @job = Job.new(params[:job])
    #if not logged in creates a user and sign in
    if !current_user
      @user = User.new(params[:job][:user_attributes])
    else
      @user = current_user
    end
    @job.user_id = @user.id
    respond_to do |format|
      if @job.save
        if !current_user
          sign_in(:user, @user)
        end
        format.html { redirect_to @job }
      else
        format.html { render action: "new" }
      end
    end
  end
  job.rb
  attr_accessible :user_attributes, :description, :name ....
  belongs_to :user
  accepts_nested_attributes_for :user

谢谢!

因为您正在调用@user.save!,它将生成一个异常。同样,这样做不会将作业与User放在同一事务中。你想要的是nested_attributes:

class Job < ActiveRecord::Base
   accepts_nested_attributes_for :user
end

如果用户已登录,请不要显示表单的这一部分并过滤这些参数。

请点击此处查看Rails文档中的更多信息http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

编辑:

简化控制器代码,因为您使用的是嵌套属性,所以不再需要手动创建用户。

#if not logged in creates a user and sign in
if !current_user
  @user = User.new(params[:job][:user_attributes]) # this is no longer needed
else
  @user = current_user
end
@job.user_id = @user.id # this is redundant

更像:

# if logged in, manually assign the user (also you may want to reject any user attributes)
@job.user = current_user if current_user

最新更新