I defined a helper function in the view:
def usernames(id) do
post = Repo.get(Post, id) |> Repo.preload(comments: :user)
usernames = for comment <- post.comments do
comment.user.username
end
end
Then in the javascript file I do:
$('#comment').doThis({
data: "<%= escape_javascript( MyApp.ApplicationHelpers.usernames(@post.id) ) %>"
});
The above does not work. Of course I need to be able to pass in the @post.id, but even by hardcoding a post id like MyApp.ApplicationHelpers.usernames(5)
, doesn't work.
Basically I am trying to do the Rails equivalent of:
@usernames = User.pluck(:username)
Then in the js.erb would have been:
data = <% @usernames %>
$('#comment').doThis({'data': data});
If someone can help out in how to achieve this...
Update: (to provide additional info)
I put the javascript code in posts.js
as following this stackoverflow answer. Other javascript code in that file executes as needed.