Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Send link_to in JSON


  • Please log in to reply
4 replies to this topic

#1 kristers_Z

kristers_Z

    Passenger

  • Members
  • 5 posts

Posted 30 October 2013 - 09:06 PM

In my View I have a list of items in database. By the side of each item in there is "delete" link.

There is also an AJAX form which allows to create new items. New items are appended to list by JS.

 

When submit button is pressed, controller should send back JSON. The problem is - how to send that "delete" link as a JSON? Since link's html has some double quotes in it, I dont get valid JSON and my JS crashes.

destroy_link  = view_context.link_to('Delete', created, method: :delete, remote: true, :class => 'minus' ) 

json = {'plural'       => created.class.name.pluralize.underscore.downcase,
	'singular'     => created.class.name.underscore.downcase,
	'created'      => created
       }.to_json

Since I dont know a lot about ajax, propably something is terribly wrong here?



#2 Ohm

Ohm

    Guard

  • Members
  • 179 posts
  • LocationCopenhagen

Posted 31 October 2013 - 06:09 AM

You shouldn't send the actual HTML back, just the link. Instead of link_to use url_for, which will just give you the "href" part of the a-tag.


Blog: http://ohm.sh | Twitter: madsohm


#3 Bharat Soni

Bharat Soni

    Dispatcher

  • Members
  • 53 posts
  • LocationAhmedabad

Posted 31 October 2013 - 12:59 PM

One easiest way to do it is like below step by step solution...................... 

 

1. you have made a link for add new item in database that's fine and send the data of item values with ajax that's also fine but the link need not to send.

 

2. After save the data get the data in any instance variable which you need in your list and the respond it by js format.

 

3. Make a js format file and send the items instance variable as local with calling the partial with javascript like(.html("<%=render :partial=>%>")).

 

4. Give any id to your list item table and append this partial at the end of table like we do in javascript.

 

5. As you see the table with your new row and delete link.


  • james likes this

Fun with Ruby on Rails


#4 kristers_Z

kristers_Z

    Passenger

  • Members
  • 5 posts

Posted 31 October 2013 - 07:05 PM

You shouldn't send the actual HTML back, just the link. Instead of link_to use url_for, which will just give you the "href" part of the a-tag.

 

This doesn't seem to work with REST, like link_to does. Am I wrong?



#5 kristers_Z

kristers_Z

    Passenger

  • Members
  • 5 posts

Posted 31 October 2013 - 07:24 PM

I mean - what's the exact code to get this done without specifying controller and action directly in parameters? Like in link_to.






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users