嵌套表单验证轨道3.2

时间:2014-10-19 14:40:55

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord devise

我在同一视图中有一个工作和用户(设计)表单。当我尝试在用户字段中提交错误时,它会给我一个包含验证消息的异常页面。提交作业字段中的错误工作正常!

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

谢谢!

1 个答案:

答案 0 :(得分:1)

因为你打电话,@user.save!会产生异常。这样做也不会将作业放在与用户相同的交易中。你想要的是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