Кнопка «Отправить» не отправляет форму, но проверяет проверки - PullRequest
1 голос
/ 27 июня 2010

Кнопка отправки работает только для проверки javascript в файле question.js, но она не выполняет основную функцию - отправку самой формы! Ваша помощь очень ценится.

` код страницы Ruby, содержащий элемент формы

<script type="text/javascript">
    loadScript("/javascripts/questions.js",function() {});
</script>

<h1 class="hdr1">Ask question</h1>

<%= link_to Profile.find(session[:user_id]).firstname,{},{:id=>"person"} %>
<% form_for(@question) do |f| %>
  <%= f.error_messages %>

<br>

<table id="newQuesTable" width="100%" cellpadding="5" border="1">
<tr>
    <td width="25%"><label>Your Question </label> - </td>
    <td><%= f.text_area :content, :rows=>5, :cols=>35, :maxlength=>500, :id=>"newQuesTxtA"%> </td>

<td width="30%"><i><label id="newQuesLabel" style="color:red;background-color:yellow;visibility:visible;"></label></i></td>

</tr>


<tr>
    <td width="25%"><%= f.label :tags %> -</td>
    <td><%= f.text_field :tags, :maxlength=>48, :id=>"tagsNewQuesTxt" %></td>
    <td width="30%"><i><label id="nquesTagsLabel" style="color:red;background-color:yellow;visibility:visible;"></label></i></td>
</tr>


<tr>
    <td>Question Scope -</td>
    <!--the open id for the hierarchy comes here-->
    <!-- the select box comes here -->
    <td> <%= f.text_field :ID_string %></td>
</tr>

</table>

<br>
    <%= f.submit 'Post Question' %> &nbsp; <%= f.submit 'Cancel', :id=>'docNewCancelButton', :type=>'reset' %>

<% end %>

<br>
<hr>
<br>

<%= link_to 'Back', questions_path %>

Код Javascript, присутствующий в файле question.js

Event.observe(window, 'load', function(){
    $('new_question').observe('submit', submitQuestionCreate);
    $('quesNewCancelButton').onClick('resetquesform')
});

function resetquesform()
{
    event.preventDefault();
    reset($('new_question'));
    return;
}

function submitQuestionCreate(event)
{

    //event.preventDefault();

    var quesfield = $('newQuesTxtA');
    var tagsfield = $('tagsNewQuesTxt');
    var labelnques = $('newQuesLabel');
    var labelnquestags = $('nquesTagsLabel');

    if((quesfield.value == "") && (tagsfield.value == ""))
    {
        event.preventDefault();
        //alert('Question and Tags field cannot be empty');
        labelnques.innerHTML = 'Question field cannot be empty!';
        labelnquestags.innerHTML = 'Please enter (some) relevant tags...';
        probchk = true;
        return;
    }

    if((quesfield.value == "") || (tagsfield.value == ""))
    {
        event.preventDefault();
        if (quesfield.value == "")
        {
            labelnques.innerHTML = 'Question field cannot be empty!';
            labelnquestags.innerHTML = "";
            probchk = true;
            return;
        }

        if (tagsfield.value == "")
        {
            labelnquestags.innerHTML = 'Please enter (some) relevant tags...';
            labelnques.innerHTML = "";
            probchk = true;


            if (quesfield.value.length > 500)
            {
                labelnques.innerHTML = 'Question too long (should be 500 characters or less)';
                probchk = true;
            }

            return;
        }

    }


    if (quesfield.value.length > 500)
    {
        event.preventDefault();
        labelnques.innerHTML = 'Question too long (should be 500 characters or less)';
        probchk = true;
        return;
    }

}

***question controller file***


    # GET /questions/1
      # GET /questions/1.xml
      def show
        @question = Question.find(params[:id])
        if !session[:user_id].nil?
           #@owner = Document.is_owner(params[:id],session[:user_id])
           @fav_count = FavouriteQuestion.count(:all,:conditions=>["question_id = ? AND profile_id = ?",@question.id,session[:user_id]])
           if FavouriteQuestion.count(:all,:conditions=>["question_id = ? AND profile_id = ?",@question.id,session[:user_id]]) > 0
               @fav_status = 1
           else
               @fav_status = 0
           end
        else
           @owner = Document.is_owner(params[:id],nil)
           @fav_status = 0
        end
        respond_to do |format|
          format.html # show.html.erb
          format.xml  { render :xml => @question }
        end
      end

      # GET /questions/new
      # GET /questions/new.xml
      def new
        @question = Question.new
        if !session[:user_id].nil?
          @question.profile_id = session[:user_id]
        end
        respond_to do |format|
          format.html # new.html.erb
          format.xml  { render :xml => @question }
        end
      end

1 Ответ

0 голосов
/ 27 июня 2010

Похоже, что вы делаете, ruby ​​на рельсы формы с проверкой JavaScript.Хотя вы можете сделать это, я бы порекомендовал начать с базовой структуры MVC.Я настоятельно рекомендую ознакомиться с некоторыми основами, которые помогут вам в этом.http://guides.rails.info/ - отличное место для начала.Я хотел бы, чтобы это было там, когда я только начинал, это избавило бы меня от большой боли:)

Вы захотите перенести свои проверки в модель.

in app/models/question.rb

class Question < ActiveRecord::Base
  validates_presence_of :question
end

больше запечено в опциях проверки здесь .

тогда вы хотите иметь контроллер для ответа на ваши события создания.в app/controller/question_controller.rb:

class QuestionsController < ApplicationController
  def new
    @question = Question.new
  end

  def create
    @question = Question.new(params[:question])

    if @question.save
      flash[:confirm] = "You have asked a question"
      redirect_to questions_path
    else
      flash[:error] = @question.errors.full_messages.join(",")
      render :action => :new
    end
  end
end

И тогда ваша config/routes.rb

map.resources :questions

Ваша форма должна выглядеть примерно так, как у вас:

<%= flash[:error] %>
<% form_for(@question) do |f| %>
  <%= f.text_field :content ...
<% end %>

вспышкасырой, я не использовал это в течение некоторого времени.Я использую плагин message_block .Вы также можете прочитать больше о том, как работает вспышка здесь

Существуют плагины, чтобы сократить некоторые из них, но я рекомендую подрезать зубы, прежде чем делать некоторые из них.Это помогает вам ориентироваться.Желаем удачи!

...