I have a order object, which have a create method like this :

 def create
    @order                           =[:order])
    # @order.status_id = "1"

    respond_to do |format|
        flash[:notice]               = 'Order was successfully created.'
        format.html { redirect_to(@order) }
        format.xml  { render :xml    => @order, :status => :created, :location => @order }
        format.html { render :action => "new" }
        format.xml  { render :xml    => @order.errors, :status => :unprocessable_entity }

I want to set the @order status_id to "1", so I have the

 @order.status_id = "1" 

But this code is not work, after I uncomment it, it still can't save "1" in the status_id in db, but other attribute can successfully store.


class Order < ActiveRecord::Base
  has_many :order_items
  belongs_to :status

Was it helpful?


You should be able to assign a string value to a relationship key and it will be converted as required. The params always come in as strings, so obviously this needs to occur for anything to be working.

This is the kind of situation where a robust unit test would help narrow down the scope of the problem. It may be one of:

  • There is an attr_accessor defined for status_id that is blocking the assignment.
  • There is a status_id= method defined which is blocking the assignment.
  • The status_id is being reset during a before_validation or before_save call.

You'd want to create a test routine that verifies this works:

def test_status_assignment
  order =

  order.status_id = '1'

  assert_equal 1, order.status_id


You could have attr_accessible in your model blocking you from assigning to that field. It does this by using a whitelist of approved fields.

Change @order.status_id = "1" to @order.status_id = 1

Ruby may be reading "1" as a string (which it is supposed to do) instead of an integer (what you are probably looking for). When you remove the quotes ruby will interpret it as an integer. If you must leave it as a string, try something like my_string.to_i or "123".to_i.

If this doesn't work, please post whatever error message you are receiving.


@order.status_id = "1"

should be

@order.status_id = 1

Or maybe

@order.status = Status.find_by_id(1)

if you have relationships set up nicely

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top