将id从一个控制器传递到另一个控制器 - RAILS 5

问题描述 投票:2回答:1

如何在输入字段中自动放置/传递product_id?

我有2个表产品和capturepages

模式

products
t.string   "name"
t.string   "description"

capturepages
t.string   "name"
t.string   "email"
t.integer   "product_id"

楷模

product.rb
has_many :capturepages

capturepage.rb
belongs_to :product

capturepages控制器

class CapturepagesController < ApplicationController
  before_action :set_capturepage, only: [:show, :edit, :update, :destroy]

  def new
    @capturepage = Capturepage.new
    @product_id = params[:product_id]
    @product = Product.find(params[:product_id])
  end

  def create
    @capturepage = Capturepage.new(capturepage_params)
    @product = @capturepage.product
    respond_to do |format|
      if @capturepage.save
        format.html { redirect_to @product.affiliatecompanylink, notice: 'Capturepage was successfully created.' }
        format.json { render :show, status: :created, location: @capturepage }
      else
        format.html { render :new }
        format.json { render json: @capturepage.errors, status: :unprocessable_entity }
      end
    end
  end


  private
    def set_capturepage
      @capturepage = Capturepage.find(params[:id])
    end

    def capturepage_params
      params.require(:capturepage).permit(:name, :email, :product_id)
    end
end

意见/ products.show.html.erb

当用户点击以下链接时:

<%= link_to "buy now", new_capturepage_path(product_id: @product.id), target:"_blank" %>

它们被定向到捕获页面页面

视图/ capturepages / _form.html.erb

<%= simple_form_for(@capturepage) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :product_id, value: @product_id %>
    <%= f.input :name, placeholder: "Your Name", label: false %>
    <%= f.input :email, placeholder: "Your Email", label: false %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "get product" %>
  </div>
<% end %>

url说明:http://localhost:3000/capturepages/new?product_id=1捕获product_id但product_id输入为空:

enter image description here

ruby-on-rails
1个回答
3
投票

当你使用simple_form时,你应该将value放在input_html中。下面的代码应该解决您的问题

<%= f.input :product_id, input_html: { value: @product_id } %>
© www.soinside.com 2019 - 2024. All rights reserved.