Sunli Jadhav Sunli Jadhav - 1 year ago 134
Ruby Question

Ruby on Rails: Calling Model method in view

I am trying to achieve Paypal integration with rails. Following this ( 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?
h2 = "#{pluralize(@order.errors.count, "error")} prohibited this order from being saved:"
- @order.errors.full_messages.each do |message|
li = message
= f.label :first_name
= f.text_field :first_name
= f.label :last_name
= f.text_field :last_name
= f.label :card_number
= f.text_field :card_number
= f.label :card_verification, "Card Verification Value (CVV)"
= f.text_field :card_verification
= f.label :card_expires_on
= f.date_select :card_expires_on, {start_year:, end_year: (, add_month_numbers: true, discard_day: true}, {class: "browser-default"}
= link_to 'PayPal', @order.paypal_url(current_user)<= link to model function
= f.submit

My Model : defined following function.

def paypal_url(return_url)
values = {
:business => '',
:cmd => '_cart',
:upload => 1,
:return => return_url,
:invoice => id

"amount_#{1}" => item.unit_price,
"item_name_#{1}" =>,
"item_number_#{1}" =>,
"quantity_#{1}" => item.quantity

"" + values.to_query


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download