dimanche 19 avril 2015

Rails 4 - update value or data attribute in form from ajax and use this updated value in an if statement

I have a Rails app in which Users can belong to one or many Teams. Users can create ideas for each team. I want the form for Ideas to look and behave slightly different depending on how many teams the user is a member of. If a user isn't a member of any teams this message will be shown: You need to create a team first, before the user can create any ideas.


The issue I'm having is that I create Teams with Ajax. In the ideas form I currently have conditions like this:



- if current_user.teams.count == 0
You need to create a team first
- else
[..]


Since I create the teams using Ajax, this message is being displayed even when the user have created his / her first team. Unless he / she reloads the page of course, then it works. But I want to have a seamless experience.


So this condition:



- if current_user.teams.count == 0


Needs to be changed into something that I can access and update from a js.erb file, and I'm not quite sure how I can achieve that.


I was thinking of possibly using a hidden_field_tag, that I can update in Ajax. But I'm not sure how my if statement in the view would look then. I have tried the following without success (I use HAML):



= hidden_field_tag "team_count", current_user.teams.count, id: :team_count

:javascript
if ($("#team_count").val > 1) {
[...]
} else {
[...]
}


Any ideas on what I should do instead?


Aucun commentaire:

Enregistrer un commentaire