Reputation: 1267
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
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:
words_path
, which is the helper method for the words resource.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:
Upvotes: 2