繁体   English   中英

Rails中未定义的方法paypal_url

[英]undefined method paypal_url in Rails

我在Rails中有一段代码,

def create
  @registration = Registration.new(registration_params)
  if @registration.save
    redirect_to @registration.paypal_url(registration_path(@registration))
  else
    render :new
  end
end

我从教程中拿走了它。 但我只需要这一行:

@registration.paypal_url(registration_path(@registration))

现在,关于我自己的控制器feed_controller ,其中

def create
  @feed = Feed.new(check_params)
end

在视图erb文件中,我放入:

@feed.paypal_url(feed_path(@feed))

在我的feed.rb(模型)中:

def paypal_url(return_path)
  values = {
    business: "merchant@gotealeaf.com",
    cmd: "_xclick",
    upload: 1,
    return: "#{Rails.application.secrets.app_host}#{return_path}",
    invoice: id,
    amount: course.price,
    item_name: course.name,
    item_number: course.id,
    quantity: '1'
  }
  "#{Rails.application.secrets.paypal_host}/cgi-bin/webscr?" + values.to_query
end

耙道:

feed GET        /:locale/feed(.:format)                     feed#index
feed#create     POST       /:locale/feed/create(.:format)
feed#new        feed_new GET        /:locale/feed/new(.:format)
feed#destroy    feed_destroy GET        /:locale/feed/destroy(.:format)
feed#edit      feed_edit GET        /:locale/feed/edit(.:format)
feed#update    feed_update GET        /:locale/feed/update(.:format) 

但是它会显示下一个错误:

<#Feed :: ActiveRecord_Relation:0x007fee24f5fc98>的未定义方法`paypal_url'

我该如何解决? 问题是什么?

更新

def index
  @current_user_is = current_user.email
  session[:email] = @current_user_is
  session[:id] = current_user.id

  unless (current_user.member.present?)
    @member = Member.new(:user_id => current_user.id)
    @member.save()
    redirect_to '/feed'
  else
    @new_feed = Feed.new
    @feed = Feed.where(:member_id => current_user.member.id)
    @category = Category.all
    render 'home/uploads'
  end
end

只需使用def self.paypal_url(return_path)而不是def paypal_url(return_path)

说明

您通过定义Class Method而不是Instance Method遇到了问题,还有其他文章对此进行了讨论。

基本的区别是,在定义时:

def self.get_some_url
  # code to return url of an instance
end

您可以轻松地获得任何对象的所需url,例如在视图中:

<% @feeds.each do |feed| %>
  <%= feeds.get_some_url %>
<% end %>

现在,在类上调用Feed.get_some_url毫无意义。 它会调用成千上万个网址吗?

但是class methods有很多用途(在定义class methods ,您不需要像self那样使用self

def get_top_5
  # code to return the top 5 most viewed feeds
end

由于这与单个实例无关,因此可以为整个Class定义它。 导致此调用: Feed.get_top_5 ,这非常有意义。


第二个问题是不了解wherefind之间的区别, 这篇文章将帮助您解决这一问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM