[英]How do i get the id of a model that i just created through form_with basically from one controller to another in Rails
Sort of new in rails so i might be doing things the wrong way show.html.erb:轨道上的新东西,所以我可能做错了show.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 %>
Right here in feature_use_path how do i get an id to pass it in order to make a delete button as i havent even created the model yet or its saved in its own controller should就在 feature_use_path 中,我如何获得一个 id 来传递它以制作删除按钮,因为我什至还没有创建 model 或者它保存在自己的 controller 中应该
_featureuse_form.html.erb: _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 %>
Plans Controller计划 Controller
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
You're right that you can't create a button ( method: :delete
or otherwise) that relies on a record that doesn't yet exist.您是对的,您无法创建依赖于尚不存在的记录的按钮(
method: :delete
或其他方式)。
Usually, a button like this would only be relevant to existing records anyway.通常,这样的按钮无论如何都只与现有记录相关。
So, it's common to see an if
statement like this:因此,常见的
if
语句是这样的:
<% if @feature_use.persisted? %>
<%= button_to 'Change' , feature_use_path(@feature_use.id) , :class => 'btn btn-primary', method: :delete %>
<% end %>
.persisted?
returns false
if the record is new and un-saved.如果记录是新的且未保存,则返回
false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.