【问题标题】:How do i get the id of a model that i just created through form_with basically from one controller to another in Rails我如何获取我刚刚通过 form_with 创建的模型的 ID,基本上从 Rails 中的一个控制器到另一个控制器
【发布时间】:2022-08-15 08:42:11
【问题描述】:

轨道上的新东西,所以我可能会以错误的方式做事显示.html.erb:

<% @feature.each do |p| %>
    <br>
    <h1><%= p.name %></h1>
   
    <%= p.unit_price %>
    <%= render partial: \"shared/featureuse_form\", locals: {feat_use: @feat_use , feature: p} %>
    <%= button_to\'Change\' , feature_use_path(1) , :class => \'btn btn-primary\'  ,method: :delete %>

<% end %>

就在 feature_use_path 中,我如何获得一个 id 来传递它以创建一个删除按钮,因为我什至还没有创建模型,或者它应该保存在自己的控制器中

_featureuse_form.html.erb:

<%= form_with model: feat_use do |f| %>
    <%= f.number_field :total_units ,value: feature.max_unit_limit  %>
    <%= f.hidden_field :feature_id, value: feature.id %>
    <%= f.hidden_field :usage_id, value: current_user.usage.id %>
    <%= f.submit \"confirm\", id: \"button\"%> 
<% end %>

计划控制器

class PlansController < ApplicationController

    before_action :authenticate_user!
    def index
        @plan = Plan.all
    end

    def show

        @plan = Plan.find(params[:id])
        @feature = @plan.features

        @feat_use = FeatureUse.new
    end
end
class FeatureUsesController < ApplicationController

  def create
        feature_use = FeatureUse.new(feature_use_params)
        feature_use.total_units = params[:feature_use][:total_units]
        feature_use.feature_id = params[:feature_use][:feature_id]
        user = current_user.usage
        feature_use.usage_id = user.id
        feature_use.save
        
    end

end
  • 不清楚您所说的“删除”按钮是什么意思。如果您还没有创建它,您的意思是您只想清除表单吗?您的控制器中有delete 操作吗?
  • 另请发布您的相关型号代码。 feature 属于模型吗?是计划吗?如果是这样发布计划和特征模型定义。

标签: ruby-on-rails


【解决方案1】:

您是对的,您不能创建依赖于尚不存在的记录的按钮(method: :delete 或其他)。

通常,这样的按钮无论如何都只与现有记录相关。

因此,经常会看到这样的 if 声明:

<% if @feature_use.persisted? %>
  <%= button_to 'Change' , feature_use_path(@feature_use.id) , :class => 'btn btn-primary', method: :delete %>
<% end %>

如果记录是新的且未保存,.persisted? 返回 false

【讨论】:

    猜你喜欢
    • 2016-12-02
    • 1970-01-01
    • 2016-04-22
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    相关资源
    最近更新 更多