我有两个数组@necklines和@skirts,分别由所有领口模型和裙子模型组成。
我尝试一次显示一条领口和一条裙子,并有两个按钮来逐渐增加或减少当前显示的元素。
我尝试通过调用@necklines[@ni]和@skirts[@si]来做到这一点,并使用按钮增加或减少@ni和@si的值。
但是,当我单击任何按钮时,元素不会改变。
这是我的 MainController.rb
def home
@necklines = Neckline.all
@skirts = Skirt.all
if @ni.nil?
@ni = 0
end
if @si.nil?
@si = 0
end
end
def increase_neck
if @ni >= @necklines.count - 1
@ni = 0
else
@ni += 1
end
redirect_to root_path
end
def decrease_neck
if @ni <= 0
@ni = @necklines.count - 1
else
@ni -= 1
end
redirect_to root_path
end
def increase_skirt
if @si >= @skirts.count - 1
@si = 0
else
@si += 1
end
redirect_to root_path
end
def decrease_skirt
if @si <= 0
@si = @skirts.count - 1
else
@si -= 1
end
redirect_to root_path
end
这是我的home.html.erb
<h1> Main#home </h1>
<div>
<div class='neckline'>
<h3> <%= @necklines[@ni].style_name %> </h3>
<div class='child inline-block-child'> <%= button_to "<", "/home/decrease_neck", method: :post %> </div>
<div class='child inline-block-child'> <%= image_tag @necklines[@ni].image %> </div>
<div class='child inline-block-child'> <%= button_to ">", "/home/increase_neck", method: :post %> </div>
</div>
<div class='skirt'>
<div class='child inline-block-child'> <%= button_to "<", "/home/decrease_skirt", method: :post %> </div>
<div class='child inline-block-child'> <%= image_tag @skirts[@si].image %> </div>
<div class='child inline-block-child'> <%= button_to ">", "/home/increase_skirt", method: :post %> </div>
<h3> <%= @skirts[@si].style_name %> </h3>
</div>
</div>
这是我的路线.rb
Rails.application.routes.draw do
get '/necklines', to: 'neckline#index'
get "/necklines/:id", to: "neckline#show"
get '/skirts', to: 'skirt#index'
get '/skirts/:id', to: 'skirt#show'
# Defines the root path route ("/")
root "main#home"
end
我怀疑错误是每次单击按钮时 @ni 和 @si 都被分配回 0,但不确定如何继续。
对混乱的代码表示歉意,让我的第一个应用程序跌跌撞撞!
要使用 Rails 按钮增量增加显示的数组元素,您可以按照以下步骤操作:
设置控制器:在控制器中定义一个操作来处理增量。例如:
class YourController < ApplicationController
def increment_element
# Retrieve the array from your model or wherever it's stored
@array = YourModel.array
# Increment the desired element
index = params[:index].to_i
@array[index] += 1
# Save the updated array if needed
# YourModel.update(array: @array)
# Redirect or render as needed
redirect_to your_path
创建路由:在 config/routes.rb 中定义路由以将操作映射到 URL:
Rails.application.routes.draw do
# Other routes...
post '/increment_element/:index', to: 'your_controller#increment_element', as: 'increment_element'
更新视图:在视图文件(例如 your_view.html.erb)中,显示数组元素以及用于递增它们的按钮:
Rails.application.routes.draw do
# Other routes...
post '/increment_element/:index', to: 'your_controller#increment_element', as: 'increment_element'