Dynamic form fields in Rails3 with jquery

前端 未结 2 881
野趣味
野趣味 2021-02-06 19:31

I am using rialscasts #74 as a guide.

I am trying to dynamically add form fields via a text-link. In the railscast episode he achieves it very nicely using the followin

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-06 20:06

    ya I was going to say -- that is a very old railscast and is using both outdated practices and an old framework. I'm gonna try to help you out.

    layouts/application.erb

    <%= javascript_include_tag :defaults %>
    

    projects/new.erb

    <%= render :partial => 'task', :collection => @project.tasks %>

    <%= add_task_link "Add a task" %>

    projects/_task.erb

    <%= fields_for "project[task_attributes][]", task do |task_form| %>

    Task: <%= task_form.text_field :name %> <%= link_to "remove", "#", :class => 'remove_task'

    <% end %>

    projects_helper.rb

    def add_task_link(name)
      # This is a trick I picked up... if you don't feel like installing a
      # javascript templating engine, or something like Jammit, but still want
      # to render more than very simple html using JS, you can render a partial
      # into one of the data-attributes on the element.
      #
      # Using Jammit's JST abilities may be worthwhile if it's something you do
      # frequently though.
      link_to name, "#", "data-partial" => h(render(:partial => 'task', :object => Task.new)), :class => 'add_task'
    end
    

    public/javascripts/application.js

    $(function(){
      // Binds to the remove task link...
      $('.remove_task').live('click', function(e){
        e.preventDefault();
        $(this).parents('.task').remove();
      });
    
      // Add task link, note that the content we're appending
      // to the tasks list comes straight out of the data-partial
      // attribute that we defined in the link itself.
      $('.add_task').live('click', function(e){
        e.preventDefault();
        $('#tasks').append($(this).data('partial'));
      });
    });
    

提交回复
热议问题