簡體   English   中英

在rails中使用check_box接受輸入

[英]accepting input using check_box in rails

我是一個初學者,正在通過Rails教程進行工作。 作業包括向頁面添加問題(可以編輯和更新/刪除問題)。 我正在嘗試讓我的“問題”表單接受來自check_box的有關是否已回答問題的輸入(包括在“更新”部分中)。

我已經在這里這里閱讀了有關check_box的文檔,並看到我需要check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0") 但是,我不確定在表單中將在哪里使用它,以及將作為object_name,method和options傳遞的內容。 任何指針將不勝感激!

控制器:

class QuestionsController < ApplicationController
  def index
    @questions = Question.all
  end

  def new
    @question = Question.new
  end

  def create
    @question = Question.new(params.require(:question).permit(:title, :body))
    if @question.save
      flash[:notice] = "Question was saved."
      redirect_to @question
    else
      flash[:error] = "There was an error saving the post. Please try again."
      render :new
    end 
  end

  def show
    @question = Question.find(params[:id]) 
  end

  def edit
    @question = Question.find(params[:id])
  end

  def update
    @question = Question.find(params[:id])
    if @question.update_attributes(params.require(:question).permit(:title, :body))
      flash[:notice] = "Question was updated"
      redirect_to @question
    else
      flash[:error] = "There was an error saving your post. Please try again."
      render :edit
    end
  end

  def destroy
    @question = Question.find(params[:id])
    @question.destroy
    redirect_to questions_path
    flash[:notice] = "The question has been deleted."
  end
end

顯示視圖:

<h1><%= @question.title %></h1>

<%= link_to "Edit", edit_question_path(@question), class: 'btn btn-success' %>

<%= link_to "Delete", @question, method: :delete, data: { confirm: "Are you sure?" }, class: 'btn btn-success' %>

<p><%= @question.body %></p>

編輯視圖:

<h1>Edit and Update Question</h1>

<div class="row">
  <div class="col-md-4">
    <p>Guidelines for questions</p>
    <ul>
      <li>Stay on topic.</li>
    </ul>
  </div>
  <div class="col-md-8">
    <%= form_for @question do |f| %>
      <div class="form-group">
        <%= f.label :title %>
        <%= f.text_field :title, class: 'form-control', placeholder: "Enter post title" %>
      </div>
      <div class="form-group">
        <%= f.label :body %>
        <%= f.text_area :body, rows: 8, class: 'form-control', placeholder: "Enter post body" %>
      </div>
      <div class="form-group">
        <%= f.submit "Save", class: 'btn btn-success' %>
        <%= link_to "Delete", @question, method: :delete, data: { confirm: "Are you sure?" }, class: 'btn btn-success' %>
      </div>
    <% end %>
  </div>

</div>

如果,例如,你有一個answered你的屬性Question模型是一個布爾值,那么所有你有你的內做form_for塊是說<%= f.check_box :answered %> 如果選中,它將評估為true,否則為false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM