Set user_id to null then add it later in rails form/model

I am trying to make an Order app where the customer creates an Order, that Order is then placed in the Order queue where a User(worker) can accept the job and begin working on it. Currently

I am trying to have no user_id being associated with an Order until a User accepts the job where their user_id is now associated with the Order so that no other User can accept that Order.

Currently an Order belongs_to :userand User has_many :orders
In my Order migration file I have t.integer :user_id, null: true

I am wondering how to make it work so that it takes the null user_id until a User accepts the job within a rails form (currently it won’t take anything).

  • rails-backbone gem error for model with two-word names: Uncaught TypeError: Cannot call method 'bind' of undefined
  • How to install system_timer gem on Windows 7
  • Chinese and Japanese character encoding issues when exporting HTML to PDF
  • not able to create rails new application with mysql version 0.3.20
  • ActiveRecord group count with zeroes
  • How to get my Facebook friends with OmniAuth in Rails?
  • Ruby on Rails: problem getting CKeditor to upload images
  • strange inability to require config/boot after upgrading to ruby 1.9.2
  • 2 Solutions collect form web for “Set user_id to null then add it later in rails form/model”

    Firstly, as mentioned by @Mark here, you need to allow optional association else it will throw error. In your order.rb

    belongs_to :user, optional: true

    You can initialize new order with order params from your controller, then assign the user_id to it when accepted by a user.


    From your form where user accepts the order,

    order = Order.find_by_id(params[:user_id])
    unless order.user_id
      redirect_to some_path, flash: 'Order already taken'

    You need to change it to:

    belongs_to :user, optional: true

    Without the second part, it will not allow you to create a record unless it is associated with a User before saving.

    EDIT: 4.1.2 gives you all your options:

    Ruby is the best programming language in the world - Ruby on Rails.