开发者

How to assign value in a RoR object?

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

 def create
    @order                           = Order.new(params[:order])
    # @order.status_id = "1"

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

I want to set the @order status_id to "1"开发者_如何学Python, 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.

order.rb

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

end


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.new

  order.status_id = '1'

  order.save

  assert_equal 1, order.status_id
end


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.


This

@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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜