Rails で remote: true を指定した任意のリンクでPOSTしたい時の話。
必要に迫られて探した結果、こんな感じになりました。
POSTしたとき、data-paramsの値がパラメータとして送られるようです。
そしてdata-paramsは、CoffeeScript を使い .data('params', 送りたいデータ)で設定できる模様。
これらを踏まえて。
Gemfile
# 追加 gem 'haml-rails' gem 'redcarpet'
config/routes.rb
# 追加 get 'markdown/index' post 'markdown/markup'
app/controllers/markdown_controller.rb
class MarkdownController < ApplicationController def markup source = ActiveSupport::JSON.decode(params[:source]) render json: {html: Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(source)} end end
app/views/markdown/index.html.haml
#markdown %p= text_area_tag :source, '', cols: 100, rows: 10 %p= link_to 'markdown to html', markdown_markup_path, remote: true, method: :post, id: 'convert' %p= text_area_tag :target, '', cols: 100, rows: 10
app/assets/javascripts/markdown.js.coffee
$(document).on 'ready page:load', ->
$('#convert').click ->
$(this).data('params', {'source': JSON.stringify($('#source').val())})
$(document).on 'ajax:success', '#markdown', (xhr, data, status) ->
$('#target').val(data['html'])
