【问题标题】:Rails Newbie: Collection Select & Controller LogicRails 新手:集合选择和控制器逻辑
【发布时间】:2014-11-16 18:26:53
【问题描述】:

我在这里阅读了许多相关问题,但我仍然不明白如何执行以下操作: 我有一个“国家/地区”模型,我想创建一个选择表单,允许用户选择模型中的任何现有国家/地区,并被重定向到该国家/地区的“显示”页面。

我的 collection_select 逻辑是:

<%= collection_select(:country, :country_id, Country.all, :id, :name, prompt: 'Select a Country') %>

<%= submit_tag "Find!", redirect_to (country.params[:id])%>

任何帮助将不胜感激!

【问题讨论】:

  • country.params[:id] 是什么?
  • country.params[:id] 只是 country_id。

标签: ruby-on-rails ruby-on-rails-4 collection-select


【解决方案1】:

Rails 使用 MVC,因此所有逻辑都应该在模型中(瘦控制器、胖模型),并且您应该选择类似 @country = Country.find(params[:country_name]) 的国家/地区。 然后在视图中它会是&lt;%= submit_tag "Find!", redirect_to country_show_path(@country) %&gt;。如果我理解你的问题,这就是答案。

【讨论】:

    【解决方案2】:

    您将需要 SelectCountryController(或您用来接收所选国家/地区的任何控制器)和您的常规 CountryController。

    选择国家控制器:

    class SelectCountryController < ApplicationController
      def index
        if params[:country_id].present?
          redirect_to country_path(params[:country_id])
        end
      end
    end
    

    选择国家视图 (app/views/select_country/index.html.erb)

    <%= form_tag "", method: :get do %>
      <%= collection_select(:country, :country_id, Country.all, :id, :name, prompt: 'Select a Country') %>
      <%= submit_tag "Find!" %>
    <% end %>
    

    国家控制器:

    class CountriesController < ApplicationController
        def show
          @country = Country.find(params[:id])
        end
    end
    

    不要忘记确保您的 routes.rb 文件中有正确的路线:

    resources :countries
    get :select_country, to: "select_country#index"
    

    【讨论】:

    • 我试过了,它构建了选择菜单,但没有重定向到 (country_id) 路径。
    • 如果它没有重定向,那一定是 params[:country_id] 没有到达那里。
    【解决方案3】:

    选择表格

    在您的表单中创建一个下拉列表:

    <%= form_tag countries_path, method: :get do %>
        <%= collection_select(:country, :country_id, Country.all, :id, :name, prompt: 'Select a Country') %>
    <%= submit_tag %>
    

    在这种情况下,我点击了contries_path,并且我指定了一个 GET 请求。表单选择的值将传递给CountriesController#show

    发布到控制器

    您可以通过参数哈希使用传递给表单的值找到国家/地区:

    class CountriesController < ApplicationController
      def show
        @country = Country.find(params[:country][:country_id])
      end
    end
    

    【讨论】:

    • 试过这个,但我得到一个错误 - “未定义的方法 `[]' for nil:NilClass” - 错误在控制器线上:@country = Country.find(params[:国家][:country_id])
    • params 有什么东西吗?尝试打印出params 并查看其中是否有countrycountry_id 的内容
    • 参数:{"id"=>"1"}
    • 那么 1 是正确的 country_id 吗?您可以通过params[:id] 访问它
    • 1 是正确的 country_id。它现在出现了,但是当我点击提交按钮时,URL 会重新加载但仍保留在主“索引”页面 - 'localhost:3000/…'
    猜你喜欢
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 2014-04-11
    相关资源
    最近更新 更多