【问题标题】:Rails template set value to array of stringsRails 模板将值设置为字符串数组
【发布时间】:2016-08-03 05:31:18
【问题描述】:

我有一个角度模块,我在其中设置了一些字符串。我还想在模板中设置一个字符串数组。

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>

控制器

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

但是输出似乎有一些转义问题。

"[&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"]

如何在 rails 模板中呈现字符串数组?

【问题讨论】:

    标签: ruby-on-rails angularjs


    【解决方案1】:

    您不应该将逻辑放在视图或控制器中:Is it bad to have fat views in rails? 需要胖模型。所以解决方案是在模型中分块数组/使用辅助函数,将其提供给控制器,最后在视图中使用。由于不知道您到底想要什么,所以这是我能做的最多的事情。

    例如:

    # controller
    def index
      @ids = MyModel.split(params[:ids]) # suppose params[:ids] are the data coming in
    end
    
    # view
    <% @ids.each do |id| %>
    # ...
    <% end %>
    

    对于 ruby​​ 处理字符串,许多帖子可能会有所帮助。例如,here

    【讨论】:

      猜你喜欢
      • 2012-01-09
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多