我正在尝试在Rails中创建一个单词计数器,Text是一个脚手架名称,但是我的 @counter变量似乎没有给出任何输出如何解决这个问题
class TextsController < ApplicationController
before_action :set_text, only: [:show, :edit, :update, :destroy]
def index
@texts = Text.all
end
def new
@text = Text.new
end
def edit
end
def create
@text = Text.new(text_params)
@counter = @text.name.split.size
end
private
def set_text
@text = Text.find(params[:id])
end
def text_params
params.require(:text).permit(:name, :string)
end
端
查看
<p id="notice"><%= notice %></p>
<%= @text.name %>
<%= @counter %>
答案 0 :(得分:0)
根据您的代码create
方法无法显示变量。您必须使用show
方法。您可以创建新的show
方法包含。
def show
@counter = @text.name.split.size
end
将您的方法create
更改为:
def create
@text = Text.new(text_params)
if @text.save
redirect_to texts_path
else
render :new
end
end
你可以去展会页面。它会显示@counter