wwli
wwli

Reputation: 2681

rails: how to tell controller / action to return json format

Here is the code generated by scaffold

      # DELETE /swimming/classtimes/1
      # DELETE /swimming/classtimes/1.json
      def destroy
        @swimming_classtime = Swimming::Classtime.find(params[:id])
        @swimming_classtime.destroy

        respond_to do |format|
          format.html { redirect_to swimming_classtimes_url }
          format.json { head :no_content }
        end

  end

This html code will send a request for html format

<a href="/swimming/classtimes/42" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a>

or rails code

<%= link_to 'Destroy', swimming_classschedule, :method =>:delete, data: { confirm: 'Are you sure?' }%>

How to tell action to return json format?

Upvotes: 0

Views: 1640

Answers (1)

zeantsoi
zeantsoi

Reputation: 26193

You need to specify that the generated <a> tag markup returns JSON. If you're using the Rails link_to helper, you can pass the data-type attribute like this:

<%= link_to 'Destroy', swimming_classschedule_path, :method =>:delete, data: { confirm: 'Are you sure?' }, "data-type" => "json" %> 

If you're looking for pure HTML markup, something like this will work:

<a href="/swimming/classtimes/42" data-confirm="Are you sure?" data-method="delete" rel="nofollow" data-type="json">Destroy</a>

Alternatively, you could simply point your href to retrieve JSON explicitly:

<a href="/swimming/classtimes/42.json" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a>

As an FYI, the second code snippet is basically the interpolation of the first one.

Upvotes: 2

Related Questions