Marcus Thornton
Marcus Thornton

Reputation: 6193

What's wrong with my rails value assignment containing a question mark?

I have Order modle and it has delivered? boolean type attribute. In rails console, Order.first.delivered? returns false, so I assume Order does have this attribute. However I have an error in my order controller, and it says my

@order.delivered? = false

, reporting

syntax error, unexpected '=' @order.delivered? = false ^`.

What's wrong with my rails value assignment?

-- Edit:

I defined an attribute delivered? in Order model, and in rails console, Order returns delivered?: boolean, so I think the attribute name includes the ? question mark.

Edit2:

In the migration file, I defined as:

def change
  add_column :orders, :delivered?, :boolean
end

Upvotes: 1

Views: 654

Answers (3)

mhaseeb
mhaseeb

Reputation: 1779

?= cannot be interpreted by ruby. This involves both the attribute of boolean entity(?) and the assignment(=), thus flummoxing the MRI(I assume you are using Ruby MRI).

It will not be able to parse ?= since there aren't any such methods available.

The better solution will be naming your attribute without the question mark and at execution time, a method delivered? will automatically be created.

Upvotes: 1

richfisher
richfisher

Reputation: 951

the issue is caused by your attribute delivered? with ?

in rails console, type Order.new.methods.select {|e| e =~ /delivered\?/}, you can see all the methods with delivered?

=> [:delivered?, :"delivered?=", :"delivered?_before_type_cast", :"delivered?_came_from_user?", :"delivered??", :"delivered?_changed?", :"delivered?_change", :"delivered?_will_change!", :"delivered?_was", :"reset_delivered?!", :"restore_delivered?!"]

But ruby can not parse delivered?= or delivered?? method properly. So I suggest you to rename your attribute from delivered? to delivered, and Rails would generate a predicate method named delivered?

Upvotes: 3

rainkinz
rainkinz

Reputation: 10394

If you're trying to set the delivered status of @order use:

@order.delivered = false

If you're checking whether it's false if a conditional clause you can just do:

if [email protected]?
 # handle not delivered

or perhaps more idiomatically:

unless @order.delivered?
 # handled not delivered

The version with a question mark at the end only reads the value of the delivered attribute.

Upvotes: 1

Related Questions