在 rails 中创建新模型时如何触发一次 JS 代码?



当有人创建新的鸡尾酒模型时,我正在尝试在我的节目页面上播放"成就解锁"JS动画。因此,它应该只播放一次,永远不要在该特定页面上再次播放。我有点纠结于如何在不为数据库中的"成就"创建单独的表的情况下做到这一点。有人有一个简单的解决方案吗?这是我的控制器(NUM、@num 和 @num2 是我为找出解决方案而创建的变量,请随意修改(:

class CocktailsController < ApplicationController
NUM = Cocktail.count
def index
@cocktails = Cocktail.all
end
def show
@cocktail = Cocktail.find(params[:id])
# @dose = Dose.new
@num = NUM
end
def new
@cocktail = Cocktail.new
end
def create
@cocktail = Cocktail.new(cocktail_params)
@num = NUM
if @cocktail.photo.attached?
@num2 = @num + 2
@cocktail.save
redirect_to cocktail_path(@cocktail)
else
redirect_to new_cocktail_path,
warning: "Sorry, you can't create a cocktail without
uploading an image"
end
end
def edit
@cocktail = Cocktail.find(params[:id])
end
def update
@cocktail = Cocktail.find(params[:id])
@cocktail.update(cocktail_params)
redirect_to root_path
end
def destroy
@cocktail = Cocktail.find(params[:id])
@cocktail.destroy
# redirect_to root_path
end
private
def cocktail_params
params.require(:cocktail).permit(:name, :photo)
end
end

我的 HTML (第一个div 是动画的 html。我当前的代码允许动画在 7 日鸡尾酒会后创建的所有鸡尾酒会页面中多次播放(:


<% if @num < 7 %>
<div id="achievement" class="">
<div class="circle"></div>
<div class="copy">
<h4>Achievement Unlocked!</h4>
<p>Here are some internet points!</p>
</div>
</div>
<% end %>

<div class="banner" style="background-image: linear-gradient(rgba(0,0,0,0.4),rgba(0,0,0,0.4)), url( <% if @cocktail.photo.attached? %> <%= cl_image_path @cocktail.photo.key %> <% else %> https://raw.githubusercontent.com/lewagon/fullstack-images/master/uikit/lunch.jpg <% end %>)">
<div class="container">
<h1><%= @cocktail.name %></h1>
</div>
</div>
<br>
<div class="center">
<%= link_to "Add A New Dose", new_cocktail_dose_path(@cocktail), class: "btn btn-ghost" %>
</div>
<div class="cards">
<% @cocktail.doses.each do |dose| %>
<div class="card" >
<div class="card-body">
<h5 class="card-title"><%= dose.ingredient.name %></h5>
<p class="card-text"><%= dose.description %></p>
<%= link_to "Delete", cocktail_dose_path(@cocktail, dose), class: "btn btn-dark", method: :delete %>
</div>
</div>
<% end %>
</div>

<br>
<div class="center">
<%= link_to "Back", root_path, class: "btn btn-ghost" %>
</div>

在创建后重定向的参数中传递该信息(它是否是第一个的信息(,并在渲染视图中检查参数[:first_time].是否存在? 并在这种情况下执行 JS。 您不需要在参数中允许它,因为它不是从视图"发布"到控制器的东西。NameError 意味着您没有定义它,发生这种情况是因为您发送了 @num2 = @num2(参数哈希中的键值对(并且您没有定义 num2 的值。你可以做num2:"我是num2"或任何东西,这将:)

最新更新