0

I have an angular module where I set a few strings. I'd also like to set an array of strings in the template as well.

application.html.erb

  <script type="text/javascript">
    angular.module('userFromServer', [])
      .service('currentUser', function() {
        <% if logged_in %>
          this.name = '<%= @User.name %>';
          this.friends = '<%= @User.profile.friends_by_uuid %>';
        <% end %>
      })
  </script>

controller

  def friends_by_uuid
    self.friends.map{|x| "puser_#{x.uuid}"} # also tried adding .to_json
  end

However the output appears to have some escaping issues.

"[&quot;puser_589b07ee-b8f1-4214-941d-0ce0b7a6703b&quot;, &quot;puser_ec7d2918-d514-4c42-91fc-641ed2958fcd&quot;]"

 var desired_output = "["puser_589b07ee-b8f1-4214-941d-0ce0b7a6703b", "puser_ec7d2918-d514-4c42-91fc-641ed2958fcd"]

How can I render an array of strings in a rails template?

user2954587
  • 4,661
  • 6
  • 43
  • 101

1 Answers1

0

You should not put logics in views or controllers: Is it bad to have fat views in rails? Fat models are expected. So the solution is chunk the array in models / using helper functions, feed it to controller, and finally use in views. Since no idea what exactly you want, this is the most I can do.

For example:

# controller
def index
  @ids = MyModel.split(params[:ids]) # suppose params[:ids] are the data coming in
end

# view
<% @ids.each do |id| %>
# ...
<% end %>

For ruby to process strings, many posts may help. For example, here.

Community
  • 1
  • 1
knh170
  • 2,960
  • 1
  • 11
  • 17