Helpful Information
 
 
Category: Ruby Programming
How to retrieve object from a

If I have a cart object which contains CartItem objects and then use partials to display them, how do I go about getting a copy of a CartItem object to a controller method.

So if a partial displaying a CartItem had this code...


<% form_remote_tag :url => { :action => :delete_from_cart, :item => cart_item } do %>
<%= submit_tag "Delete" %>
<% end %>

...then how do I access the CartItem object from the delete_from_cart method.

At the moment I'm just trying to print out the name of the CartItem using something like...


def delete_from_cart
print params[:item].name
#or maybe
my_item = CartItem.new(params[:item])
print my_item.name
end


...but neither work so obviously I've completely misinterpreted rails again. I get an error like.

NoMethodError (undefined method `name' for "#<CartItem:0x47dd9f4>":String):
Note that I can go <%= cart_item.name %> from the partial and it prints to the browser fine, so there is a name method.

Any help will be great.

Perhaps what you're passing to the partial is not a CartItem object. You could be passing some other object in with the variable name cart_item (Notice the case and the spelling). For instance:


product = Product.find(id)
render :partial => 'partial_template', :locals => { :cart_item => product, :header => 'hello' }

In this case, what is being passed to cart_item is an instance of an object Product, which may actually have a name method. Hence, when your partial does:


<%= cart_item.name %>

it then works correctly.

One quick way to verify if you're passing a different object to the partial is by doing this:


<%= cart_item.inspect %>

which should tell you what the object is.










privacy (GDPR)