Passed parameters not being read in Rails

試著忘記壹切 提交于 2019-12-13 06:49:11

问题


I posted this question earlier: Passing parameters on button click in Rails

And the answer works very well. However, I the passed parameters aren't able to be called in erb, even the @event_option_id that is being passed from the book_now method.

It is showing in my server logs as Parameters: {"event"=>"4", "event_option_id"=>"5"} but when I try to use <%= @event_option_id %> it comes back blank, and when I just tested it as to_i, it showed 0 instead of 5.

My EventsController has this method:

def book_now
  @event_option_id = params[:event_option_id]
end 

And my link is passing the parameters like this:

<%= link_to "Book This Event Now!", book_now_path(:event => @event.id, :event_option_id => e.id), :id => "book-now-button", :class => "button" %>

I am trying to pass this @event_option_id so that I can access the corresponding values from my db.

Each EventOption has a price, description, and name that is unique to it, and when I try to access those in multiple ways, I get (NoMethodError: undefined method 'price' for nil:NilClass), for instance.

Any idea what's going on?


回答1:


With @event_option_id = params[:event_option_id] you are just assigning the event_option_id param value to an instance variable.

What you should be doing is finding the corresponding EventOption object with the event_option_id as follows:

@event_option = EventOption.find(params[:event_option_id])

With that piece of code in the controller method, <%= @event_option.price %> in the view will show the price of that EventOption object.



来源:https://stackoverflow.com/questions/39048592/passed-parameters-not-being-read-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!