2015-09-17 35 views
-2

我試圖讓Rails中一個字計數器,文字是一種腳手架的名字,但我 @counter變量似乎並沒有被賦予任何輸出如何解決這個@counter沒有給出輸出 - Rails的

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 

VIEW

<p id="notice"><%= notice %></p> 

<%= @text.name %> 

<%= @counter %> 

+1

什麼在'@ text.name'? –

+0

應該算作課本的文本 –

+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

+0

'@ text.name'將被設置爲傳遞的參數,這意味着'@counter = @ text.name.split.size'可以工作。我猜他沒有使用'create.html.erb'文件 –

+0

是的,你是對的,它不會創建'create.html.erb'。你想要顯示哪個頁面的參數? – akbarbin

+0

這不是我的代碼 –