2

Jquery を使用して、Rails 3 アプリでフィールドのグループを追加および削除する方法を見つけようとしています。jquery スクリプトをプレーンな html で使用できるようにしました。これは、http: //jsfiddle.net/beehive/ABvFH/1/で確認できます。

ただし、これを Rails 3 に変換する方法がわかりません。より具体的には、これを機能させるには、application.js ファイルの「formfield」を何に置き換えればよいでしょうか?

アプリケーション.js

$(document).ready(function() {

    $(function() {
        var x = $('#uploadform');
        var i = $('#uploadform ul').size() + 1;

        $('#addmore').live('click', function() {
            if ($(".item", x).length < 9) {
                $('<ul class="item" class="field">formfield ' + i + ' <a href="#" id="remfields">Remove</a></p>').appendTo(x);
                i++;
            }
            return false;
        });

        $('#remfields').live('click', function() {
            if (i > 2) {
                $(this).parents('ul').remove();
                i--;
            }
            return false;
        });
    });​


});

form.html.erb

<%= form_for(@upload) do |f| %>
  <% if @upload.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@upload.errors.count, "error") %> prohibited this upload from being saved:</h2>

      <ul>
      <% @upload.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <h2><a href="#" id="addmore">Add More Fields</a></h2>
  <div id="uploadform">
    <ul class="field">
      <li>
        <%= f.label :title %><br />
        <%= f.text_field :title %>
      </li>
      <li>
        <%= f.label :genre %><br />
        <%= f.collection_select :genre, Upload::GENRES, :to_s, :to_s, :include_blank => true %>
      </li>
      <li>
        <%= f.label :category %><br />
        <%= f.collection_select :category, Upload::CATEGORIES, :to_s, :to_s, :include_blank => true %>
      </li>
      <li>
        <%= f.label :age %><br />
        <%= f.collection_select :age, Upload::AGES, :to_s, :to_s, :include_blank => true %>
      </li>
    </ul>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
4

2 に答える 2

0

それを機能させるために私がしなければならなかったのはコメントだけです$(function() {

$(document).ready(function() {

    //$(function() {
        var x = $('#uploadform');
        var i = $('#uploadform ul').size() + 1;

        $('#addmore').live('click', function() {
            if ($(".item", x).length < 9) {
                $('<ul class="item" class="field">formfield ' + i + ' <a href="#" id="remfields">Remove</a></p>').appendTo(x);
                i++;
            }
            return false;
        });

        $('#remfields').live('click', function() {
            if (i > 2) {
                $(this).parents('ul').remove();
                i--;
            }
            return false;
        });
    //});​


});

編集:

それらを挿入するとはどういう意味ですか?

要素にアクセスするには、それらをループできます

    $('#uploadform > ul').each(function(index) {
        alert(index + ': ' + $(this).text());
    });

生成された HTML に注目してください。各 li (リスト項目) に対して ul (順序なしリスト) を作成しています。リスト項目のみを追加するように修正することをお勧めします。

于 2012-07-11T18:59:04.977 に答える
0

フォームを送信する前に、ユーザーが多くのアップロードを追加できるようにしたいと思います。その場合、レールのネストされた属性を使用しています。

これが例です。注文には多くの写真があります

注文モデル:

class Order < ActiveRecord::Base
  has_many :photos, :dependent=>:destroy, :inverse_of=>:order
  accepts_nested_attributes_for :photos, :allow_destroy=>true,:reject_if=> :all_blank
end

写真のモデル:

class Photo < ActiveRecord::Base
  has_attached_file :photo
  belongs_to :order
end

注文フォーム ビュー:

<%= form_for @order, :html => {:autocomplete => :off, :multipart => true} do |f| %>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
    <h3>Order photos</h3>
        <%= f.fields_for :photos do |photo| %>
        <%= render :partial=>'photo_form', :object=> photo, :as => :f %>
        <% end %>
    <%= link_to 'Add photo', new_photo_path, :remote=>true, :id=>'add_photo'  %>
    <%= f.submit%>
<% end %>

photo_form 部分:

<fieldset class="photo" data-status="<%= f.object.persisted? ? 'db':'new' %>">
   <% if f.object.persisted? %>
      <div class="field">
    <label>Photo:</label><br />
    <%= link_to f.object.photo.url, :target=>'_blank' do %><%= image_tag f.object.photo.url(:mini) %><% end %>
      </div>
   <% else %>
      <%= f.label :photo
      <%= f.file_field :photo %>
      <%= f.text_field :description %>
  <%= f.check_box :_destroy, :class=>'delete' %>
</fieldset>

コントローラーで、写真の注文を編集するには、edit、update、add_photo (ユーザーが写真リンクの追加をクリックしたときの ajax アクション) の 3 つのアクションが必要です。

class OrdersController < ApplicationController
  def edit
    @order = Order.find(params[:id])
  end

  # Action responsible for updating existing order record
  def update
    @order = Order.find(params[:id])
    if @order.update_attributes(params[:order])
       redirect_to @order, :notice=>'Order updated'
    else
       render :action => "edit" #save error, display order form with errors
    end
  end

  # Action responsible for creating nested form for order photo
  def new_photo
    #nothing just renders 'new_photo.js.erb'
  end
end

new_photo.js.erb:

$object=$("<%= escape_javascript( render(:partial => "photo_form", :locals=>{
    :f=>FormBuilder.new("order[photos_attributes][#{rand(400000)}]",Photo.new(),self,{},proc {})
}) ) %>").hide();  //generates new photo view
$object.insertBefore("a#add_photo").slideDown(500); 

これは単なる例ですが、これをアプリケーションに採用しても問題はありません。

于 2012-07-11T19:34:22.440 に答える