Dan
Dan

Reputation: 1267

Rails, create object using AJAX

In Rails app there is a User model and User has many Words. There is a table with many items (show action in items controller), each item is represented by row which has a word and link (that will be used to create a record). How to create a word record associated with user based on row data using AJAX? For example, the row has word 'test', and when the link is clicked new Word record should be created and appended to the current user's words.

I tried to give each link remote: true attribute and make AJAX request in show.js.erb (because links are in the show action) which is called each time the link is clicked, but there is no way to find out which link was clicked, so I cannot extract any info from the row.

The AJAX request looks like this:

$.ajax({
  type: "POST",
  url: "/users/<%= current_user.id %>/words/",
  data: { word: { word: word, translation: translation, context: context } },
});

Create action in WordsController:

def create
  @words << Word.new(filter_params)
  redirect_to user_words_path
end

Any help would be great.

Upvotes: 2

Views: 1866

Answers (1)

gwcoffey
gwcoffey

Reputation: 5921

In rails you can put remote: true on any link to make it ajax-y. In your case it sounds like the problem is you don't have a legitimate link to a create action. So what you need is:

First: A create action in the Words controller:

def create
   @word = Word.new(word_params)
   @word.user = current_user
   @word.save!
end

...

private
def word_params
   params.require(:word).permit(:word, :translation, :context)
end

Second: A link to the create action on your page:

<%= link_to(
   "Test",
   words_path(word: "Test", translation: "foo", context: "bar"),
   method: :post,
   remote: true 
) %>

The important points are:

  1. You link to the words_path, which is the helper method for the words resource.
  2. You set the method to post to inform your controller that you want the create action.

You can find the mapping of helpers and methods to controller actions by running rake routes.

A few caveats:

  1. I don't really know your model well enough but it looks from your question like Word has columns word, translation, and context, and an association to a user. Adjust the above code as needed.
  2. You might want to make your create action smarter than I have shown above. My version will simply raise an exception if you fail validation. I leave it to you to make it do what you need.

Upvotes: 2

Related Questions