Yuli
Yuli

Reputation: 151

Why fails to assign value to attribute in controller?

I'm doing the last exercise in chap 13 of the book "Agile Web Development with Rails".

Previously there was a model named "Order" and I created a migration to add a column named "ship_date":

add_column :orders, :ship_date, :datetime

Then I added a line in "create" action in the orders_controller before respond_to like this:

@order.ship_date = Time.now.to_date

Then I modified the test file like this:

ship_date_expected = Time.now.to_date  ### new line
post_via_redirect "/orders",
                  order: { name:     "Dave Thomas",
                           address:  "123 The Street",
                           email:    "[email protected]",
                           pay_type: "Check",
                           ship_date: Time.now.to_date } ### new line
### some existing lines
assert_equal ship_date_expected, order.ship_date  ### new line

Then I run the integration test but get failures like this:

test_buying_a_product(UserStoriesTest)[H:/Sites/rails_projects/depot/test/integration/user_stories_test.rb:56]:<Tue, 22 Jan 2013> expected but was <nil>.

I checked the database and was sure the new column exists. So I guessed the problem is about the assignment. This should be a dumb problem ... but I don't know how to fix it. Could anyone help me?

ThX!!!

The create action:

def create
  @order = Order.new(params[:order])
  @order.add_line_items_from_cart(current_cart)
  @order.ship_date = Time.now.to_date

  respond_to do |format|
    if @order.save
      Cart.destroy(session[:cart_id])
      session[:cart_id] = nil
      OrderNotifier.received(@order).deliver
      format.html { redirect_to store_url, notice: I18n.t('.thanks') }
      format.json { render json: @order, status: :created, location: @order }
    else
      @cart = current_cart
      format.html { render action: "new" }
      format.json { render json: @order.errors, status: :unprocessable_entity }
    end
  end
end

Upvotes: 1

Views: 285

Answers (2)

gqli
gqli

Reputation: 1045

I encountered the same error, It's because i forgot to update order_params. You need to grant the permission to :ship_date, Otherwise the date value won't be able to save in the ship_date column. That's also the reason why you get nil

 def order_params
  params.require(:order).permit(:name, :address, :email, :pay_type, :ship_date)

Upvotes: 0

Chowlett
Chowlett

Reputation: 46667

Remember you need to save your @order after making the assignment!

Upvotes: 1

Related Questions