Rails 关于渲染 create.js.erb 文件

stephen · December 20, 2011 · Last by glorySpring replied at October 29, 2012 · 6511 hits

我的代码

respond_to :js

def create
     @user = .......
     respond_with @user if @user.save
end

而 views/users 文件夹下,只有 create.js.erb,里面有一句代码 alert('aaaaa');

但是提交表单后,最后跳转是跳转去了 localhost/users

没触发 alert,没渲染到 create.js.erb 文件,

请问哪里错误了?

form 需要有 remote => true 参数

已经有了 form_for @xxx, :remote => true, :html => {:multipart=>true}

难道上传文件,不能 remote???

其实我要实现的功能,类似帖子 + 留言,留言的 form 在帖子的 show 里,只不过我的 form 是上传文件!

#2 楼 @stephen 那多贴点代码(注意看回复框下面的回帖格式)

View:

<%= form_for @microphoto, :remote => true, :html => {:multipart => true} do |f| %>
    <div class="modal-body">
        <%= f.file_field :photo %>
    </div>

    <div class="modal-footer">
        <%= f.submit "上传", :class => 'btn primary' %>
    </div>
<% end %>

Controller:

def create
  @microphoto = current_user.microphotos.build(params[:microphoto])
  @microphoto.save
  render(:json => @microphoto.to_json, :layout => false)
end

上面 render 这里乱写的,应为不断在测试 route.rb

resources :microphotos,   :only => [:create, :index]

@huacnlee 视图文件夹下只有 create.js.erb 一个文件,index 的 action 我是直接返回 json 的,我不明白就是,一提交,他一定会转到 localhost/microphotos

哦,没有加 jquery_ujs

看 ruby-china 的 application.js 和 Gemfile

@huacnlee 加了,有的! //= require jquery //= require jquery-ui //= require jquery_ujs //= require autocomplete-rails //= require_tree .

其实我有另外一个是用了 remote,是成功的,不过那个不是上传文件,这个是,真郁闷

@huacnlee 我把 form 的 remote => true 去掉,提交后的效果一样,是不是证明 remote => true 失效了,但是我看源代码,有生成 data-remote="true"

实在太无聊了!!!原生的文件上传不能用 remote,只能自己写,或者用插件!推荐插件https://github.com/leppert/remotipart

#14 楼 @stephen 嗯,我也有相同的问题,这个插件能解决你的问题嘛?

#17 楼 @stephen 问一下 问什么 我在 production 模式下发布程序 以后 js.erb 文件还是无法调用到呢?我是按照 github 上的说明配置的,可是在 production 模式下还是调用不到,可是在 development 模式下可以,是不是有什么地方要注意一下呢?

#17 楼 @stephen 啊,找到问题了。。呵呵,漏眼了。谢了兄弟、、、

You need to Sign in before reply, if you don't have an account, please Sign up first.