Sunli Jadhav Sunli Jadhav - 5 months ago 25
Ruby Question

Ruby on Rails: Calling Model method in view

I am trying to achieve Paypal integration with rails. Following this (http://railscasts.com/episodes/141-paypal-basics) I have a function in model which call paypal service with a return url. I have added a link in view that links to method in model.But some how rails is not able to get function in model.

What am i doing wrong?

My View :

form_for @order do |f|
- if @order.errors.any?
#error_explanation
h2 = "#{pluralize(@order.errors.count, "error")} prohibited this order from being saved:"
ul
- @order.errors.full_messages.each do |message|
li = message
.field
= f.label :first_name
= f.text_field :first_name
.field
= f.label :last_name
= f.text_field :last_name
.field
= f.label :card_number
= f.text_field :card_number
.field
= f.label :card_verification, "Card Verification Value (CVV)"
= f.text_field :card_verification
.field
= f.label :card_expires_on
= f.date_select :card_expires_on, {start_year: Date.today.year, end_year: (Date.today.year+10), add_month_numbers: true, discard_day: true}, {class: "browser-default"}
.field
= link_to 'PayPal', @order.paypal_url(current_user)<= link to model function
.actions
= f.submit


My Model : defined following function.

def paypal_url(return_url)
values = {
:business => 'xxxxx.XXXXX@techflex.com',
:cmd => '_cart',
:upload => 1,
:return => return_url,
:invoice => id
}

values.merge!({
"amount_#{1}" => item.unit_price,
"item_name_#{1}" => item.product.name,
"item_number_#{1}" => item.id,
"quantity_#{1}" => item.quantity
})

"https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query


end

Error :

NoMethodError in Orders#new
Showing C:/Users/Suniljadhav/SourceCode/TrainStation/app/views/orders/_form.html.slim where line #24 raised:

private method `paypal_url' called for #<Order:0x5e49bf8>
Trace of template inclusion: app/views/orders/new.html.slim


Rails.root: C:/Users/Suniljadhav/Source Code/TrainStation

Answer

It seems that paypal_url is a private method and you are trying to call it from outside of its class.

In your Order class you probably have the keyword private. Every method below that keyword will be declared private (as opposed to public) and an error will be thrown if you try to call it from outside the class. Private methods can only be called from within the class where they are defined. So try moving the definition of paypal_url so that it appears before private in your class.

You can read more about how this works here, and about the reasons behind it here.