ruby-china 代码 controller 里面 action 为什么都没有 respond_to,而我用 scaffold 生成里面有。ruby-china 做了特殊处理?
respond_to 可以针对 :html, :json, :xml 做不同的输出
respond_to
http://api.rubyonrails.org/#respond_to respond_to(*mimes, &block) 需要同时返回多种 mime_type 的时候这么做才比较好,不然就是多余的. ruby-china 论坛里面大多返回 html,所以直接render html:,api 返回 json,用render json: or render text:
respond_to(*mimes, &block)
render html:
render json: or render text:
#1 楼 @cisolarix 在 create 中没有写下面这段代码也是可以个根据 MIME 类型做不同的输出吧:
respond_to do |format| if @course.save format.html { redirect_to @course, notice: 'Course was successfully created.' } format.json { render :show, status: :created, location: @course } else format.html { render :new } format.json { render json: @course.errors, status: :unprocessable_entity } end end
ruby-china 的回复帖子功能里面,返回的就是 create.js.erb.而在 create 里面没有 respond_to,只有如下代码:
def create @reply = Reply.new(reply_params) @reply.topic_id = @topic.id @reply.user_id = current_user.id if @reply.save current_user.read_topic(@topic) @msg = t('topics.reply_success') else @msg = @reply.errors.full_messages.join('<br />') end end
#3 楼 @rdongxie jquery_ujs
#4 楼 @flowerwrong jquery_ujs 仅仅是 ajax 调用吧,没有涉及到 controller。jquery_ujs 发送请求 MIME_TYPE:application/javascript。
#5 楼 @rdongxie 结合 rails 做的就很多了. https://github.com/rails/jquery-ujs/wiki
#6 楼 @flowerwrong ok,我测试下。
#6 楼 @flowerwrong 我测试了下,两个表单,一个使用 jquery_ujs,一个没有使用,controller 里面没有 respond_to 代码块,可以同时相应,我建立了 2 个 view create.js.erb create.html.erb。