rails 3 and jquery railscast 197 issues

假如想象 提交于 2019-12-12 02:46:15

问题


Im doing railscast episode 196-197, everything works fine except that no "add answers","add question" just "remove question", Im working with ruby1.9.2 and rails 3.1.1, I know the episode is in rails 2.3, but must be something like a = or % that I miss...at the end of the episode, give a option for jquery but not works to me,please help! thanks in advance.


回答1:


Thanks DeathHammer. This fixed the same issur for me.

It was the syntax changes in Rails 3 for the helper method that did it.

Railscast ex:

link_to_function(name, h("add_fields(this, \"#{association}\", \"#escape_javascript(fields)}\")"))

Your working ex:

link_to_function(name, ("add_fields(this, '#{association}', '#{escape_javascript(fields)}')"))



回答2:


As you have not provided any detail so I am writing based on my own assumption. Write this in your application_helper.rb

def link_to_remove_fields(name, f)
    f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)")
  end

  def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, ("add_fields(this, '#{association}', '#{escape_javascript(fields)}')"))
  end

write this in your application.js

function remove_fields (link) {
  $(link).prev("input[type=hidden]:first").val('1');
    $(link).closest(".fields").hide();

}

function add_fields(link, association, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + association, "g")
  $(link).parent().before(content.replace(regexp, new_id));

}

This is somewhat how your view will look:

<%= f.fields_for :uploads do |upload| %>
    <div class="fields">
      Upload Photo: <%=upload.file_field :photo %>
    </div>
<% end %>
<p> <%= link_to_add_fields 'Need to upload More files? Please click here.', f, :uploads %> </p>

create a partial with a _modelname_fields.html.erb and it should have only that field ( for me its a file upload fields) like this

<div class="fields">
  Upload Photo: <%=f.file_field :photo %>
</div>
<br />

Try it out.



来源:https://stackoverflow.com/questions/8895193/rails-3-and-jquery-railscast-197-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!