【问题标题】:How to save simple_form_for field in a différent controller ruby on rails如何在rails上的不同控制器ruby中保存simple_form_for字段
【发布时间】:2017-11-29 19:40:37
【问题描述】:

Rails 版本 5.1.4

你好,

我无法将我的 simple_form_for 的字段值 immo_type 保存到我的控制器 Pages

#app\controllers\pages_controller.rb
class PagesController < ApplicationController
  skip_before_action :configure_permitted_parameters, only: [:home]

  def home
    @purchase = Purchase.new
    @immo_type = params[:immo_type]

  end
end

观点:

#app\views\pages\home.html.erb    
<%= simple_form_for @purchase, url: purchases_path(@purchase), :method => :post do |f| %>
  <%= f.input :address %>
  <%= f.input :immo_type %>
  <%= f.button :submit, "Search" %>

型号:

#app\models\purchase.rb
class Purchase < ApplicationRecord
    belongs_to :user
    has_many :users, :through => :searches
end

对不起,我是 ruby​​ on rails 的新手!!!

我尝试在我的 Pages 控制器中输入 &lt;%= debug params %&gt; 或“raise”。我有这条消息

--- !ruby/object:ActionController::Parameters 参数:!ruby/hash:ActiveSupport::HashWithIndifferentAccess 控制器:pages 行动:允许回家:假

你能帮帮我吗?

【问题讨论】:

  • 应该有一个创建动作来保存表单数据
  • Purchase 和 Immo_Type 有关系吗?
  • immo_type 属于购买Tab 作为地址

标签: ruby-on-rails strong-parameters simple-form-for


【解决方案1】:
class PagesController < ApplicationController
  skip_before_action :configure_permitted_parameters, only: [:home]

  def create
      purchase=Purchase.new(purchase_params)
      if purchase.save
       flash[:notice] = "purchase saved successfully."
       redirect_to root_path
      else
       flash[:error] = purchase.errors.full_messages.to_sentence
       redirect_to :back
      end
    end

    private
    def purchase_params
      params.require(:purchase).permit(:address,immo_type)
    end
end

【讨论】:

    【解决方案2】:

    所以,首先我需要使用带有主页和索引视图的搜索控制器

    class SearchesController < ApplicationController
    
        def home
            @searches = params[:immo_type]
        end
    
        def index
            @purchases = Purchase.search_by_immo_type_and_address("#{params[:purchase][:immo_type]}")
        end
    end
    

    这是我使用 Pg_Search gem 购买的模型

    class Purchase < ApplicationRecord
        belongs_to :user
        has_many :users, :through => :searches
    
        include PgSearch
        pg_search_scope :search_by_immo_type_and_address, against: [:immo_type]
    end
    

    还有 simple_form_for 的视图

    <%= simple_form_for :purchase, url: searches_url, method: :get do |f| %>
                <%= f.input :address %> 
                <%= f.input :immo_type %>
                <%= f.button :submit, "Rechercher"%>
    <% end %>
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 2019-09-21
      相关资源
      最近更新 更多