Rails 4 - 找不到包含'id'的订阅

时间:2016-11-03 12:23:33

标签: ruby-on-rails-4

问题:有人可以告诉我如何调整我的方法与网址相关联以避免error Couldn't find Subscription with 'id'=,具体取决于用户选择哪种付款方式&显示的网址 - 我将在下面解释清楚:

  • 我有2个网址
  • [选项付款1] 当用户选择付费选项参加活动时,系统会将用户定向到付款新页面,并显示此网址:http://localhost:3000/payments/new?event_id=2&user=4
  • [选项付款2] 当用户选择订阅选项时,系统会将用户定向到付款新页面,并显示此网址:http://localhost:3000/payments/new?subcription_id=1&user=4

payments_controller.rb的{​​{1}}文件中,我有以下方法:

new

当用户选择 [选项付款1] 并被定向到带有显示网址def new @subscription = Subscription.find(params[:subcription_id]) @subcription_id = params[:subcription_id] @event = Event.find(params[:event_id]) @event_id = params[:event_id] @payment = Payment.new end 的付款新页面时,我会收到以下错误

http://localhost:3000/payments/new?event_id=2&user=4
  

问题:

有人可以建议我如何调整我的方法以与网址相关联以避免错误Couldn't find Subscription with 'id'= ,具体取决于用户选择哪种付款方式&显示的网址

我试过以下但没有运气:

Couldn't find Subscription with 'id'=

我也试过这个但没有运气:

def new
    if @subscription.present?
      @subscription = Subscription.find(params[:subcription_id])
      @subcription_id = params[:subcription_id]
    elsif @event.present?
      @event = Event.find(params[:event_id])
      @event_id = params[:event_id]
    end
    @payment = Payment.new
  end

enter image description here

2 个答案:

答案 0 :(得分:1)

只需根据参数是否存在来查找。

def new
  @subscription = Subscription.find(params[:subcription_id]) if params[:subscription_id].present?
  @subcription_id = params[:subcription_id]
  @event = Event.find(params[:event_id]) if params[:event_id].present?
  @event_id = params[:event_id]
  @payment = Payment.new
end

或者更清楚......

def new
  if params[:subscription_id].present?
    @subscription = Subscription.find(params[:subcription_id])
    @subcription_id = params[:subcription_id]
  end
  if params[:event_id].present?
    @event = Event.find(params[:event_id]) 
    @event_id = params[:event_id]
  end
  @payment = Payment.new
end

答案 1 :(得分:0)

以下为我工作:

def new
    @subcription_id = params[:subcription_id]
    @event_id = params[:event_id]
    @payment = Payment.new
    if @subcription_id.present?
      @subscription = Subscription.find(params[:subcription_id])
    elsif @event_id.present?
     @event = Event.find(params[:event_id])
    end
  end