【问题标题】:Select Tag, undefined method `map'选择标签,未定义方法`map'
【发布时间】:2015-08-03 20:05:18
【问题描述】:

我有一个订阅表单,我试图在其中设置用户选择的计划、他们希望与订阅相关联的业务以及付款详细信息。在我的表单中,我使用一个选择标签来显示所有企业的列表,它在我的视图中正确显示,但保存后我收到以下错误:

undefined method `map' for #<Business:0x007f8ea7955b90>

new.html.erb

<div class="field">
  <%= select_tag :business_id, options_from_collection_for_select(@businesses, "id", "name") %>
</div>

subscriptions_controller.rb

...

def new
  @subscription = Subscription.new
  @plan = Plan.find(params["plan_id"])
  @businesses = Business.all
end

def create
  @subscription = Subscription.new(subscription_params)
  raise "Please, check subscription errors" unless @subscription.valid?
  @subscription.process_payment
  @subscription.save
  redirect_to @subscription, notice: 'Subscription was successfully created.'
rescue => e
  flash[:error] = e.message
  render :new
end

private

  def set_subscription
    @subscription = Subscription.find(params[:id])
  end

  def subscription_params
    params.require(:subscription).permit(:plan_id, :business_id, :card_token, :coupon)
  end

我是否正确设置了 select_tag?我需要修复我的创建方法吗?在 SO 上查看了其他解决方案,但收效甚微。

【问题讨论】:

  • 您能从错误堆栈跟踪的顶部添加一些行吗?我认为最多十行就足够了。
  • @amar47shah 上面的图片有帮助吗?
  • 是的,这确实有帮助。看起来create 操作试图再次呈现new 模板,可能是因为新订阅无效。请注意,render :new 不会在控制器中调用 new 操作。不过,我仍然很难说出发生了什么事。看起来@businesses 的值已经从一个集合变成了一个单一的业务,但我不知道为什么。仅出于调试目的,尝试在create 操作的rescue 块中再次设置@businesses = Business.all。哦等等,现在我有个主意了!
  • @amar47shah 我正在提取业务集合,以便用户可以从我的所有业务中选择他们想要开始订阅的业务之一。
  • @amar47shah 你还有解决方法的想法吗?

标签: forms ruby-on-rails-4


【解决方案1】:

Rails 为每个请求实例化一个新控制器。有一些关于 here 的信息。

这意味着当您在create 中处理 POST 时,您在 new 中设置的任何实例变量都将不可用。

在您的情况下,当新订阅验证失败时,您将在 create 操作的救援块中呈现 :new 模板。此时您只会收到错误,而不是在您最初访问表单时。

问题是render :new 没有调用new 动作;它只是呈现模板。在订阅未通过验证并重新呈现表单的情况下,此控制器实例从未调用过 new 操作,并且实例变量不具有模板预期的值。

试试这个而不是render :new

redirect_to new_subscription_url

这将实例化一个新控制器并调用new 操作,这样您就可以从头开始。 new 模板中所需的实例变量将在模板渲染之前被分配正确的值。

作为替代方案,您可以在救援块中设置实例变量:

def create
...
rescue => e
  flash[:error] = e.message
  @businesses = Business.all
  render :new
end

这是 Stack Overflow 上类似的 question

希望对您有所帮助。编码愉快!

【讨论】:

    猜你喜欢
    • 2013-09-19
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    相关资源
    最近更新 更多