重构:如何在 Rails 更新操作中高效渲染 json

发布于 2024-11-03 16:17:03 字数 1821 浏览 2 评论 0原文

如何重构此代码,以便在 json 对象使用相同的基本格式时不会一遍又一遍地重复它们?我对 Ruby on Rails 仍然有点不舒服,所以我不确定解决这个问题的最佳方法。

  # PUT /users/:user_id/profile/:id
  def update
    if request.xhr?
      profile = current_user.profile

      if params[:profile].blank?
        render :json => { :error => "There was no profile data passed in so your profile could not be saved." }, 
               :status => :unprocessable_entity
      else
        if profile.update_attributes(params[:profile])
          render :json => { :interests => 
                              simple_format(h(profile.interests), :class => "pbs tl"),
                            :favorite_music =>
                              simple_format(h(profile.favorite_music), :class => "pbs tl"),
                            :favorite_movies =>
                              simple_format(h(profile.favorite_movies), :class => "pbs tl"),
                            :favorite_books =>
                              simple_format(h(profile.favorite_books), :class => "pbs tl"),
                            :favorite_foods =>
                              simple_format(h(profile.favorite_foods), :class => "pbs tl") },
                 :status => :ok
        else
          render :json => { :error => get_errors_for_class(profile).to_sentence }, 
                 :status => :unprocessable_entity
        end
      end
    end
  end

更新:我对原始答案做了一些修改,它对我有用。这是我的修改:

  # within profile.rb
  # create a hash of profile attributes
  def html_to_hash
    %w{interests favorite_music favorite_books favorite_foods}.inject({}) do |hash, property|
      hash[property] = simple_format(h(self.send(property)), :class => 'pbs tl')
      hash
    end    
  end

How can I refactor this code so I don't repeat the json objects over and over again when they use the same basic format? I'm still a bit uncomfortable with Ruby on Rails so I'm unsure of the best way to approach this.

  # PUT /users/:user_id/profile/:id
  def update
    if request.xhr?
      profile = current_user.profile

      if params[:profile].blank?
        render :json => { :error => "There was no profile data passed in so your profile could not be saved." }, 
               :status => :unprocessable_entity
      else
        if profile.update_attributes(params[:profile])
          render :json => { :interests => 
                              simple_format(h(profile.interests), :class => "pbs tl"),
                            :favorite_music =>
                              simple_format(h(profile.favorite_music), :class => "pbs tl"),
                            :favorite_movies =>
                              simple_format(h(profile.favorite_movies), :class => "pbs tl"),
                            :favorite_books =>
                              simple_format(h(profile.favorite_books), :class => "pbs tl"),
                            :favorite_foods =>
                              simple_format(h(profile.favorite_foods), :class => "pbs tl") },
                 :status => :ok
        else
          render :json => { :error => get_errors_for_class(profile).to_sentence }, 
                 :status => :unprocessable_entity
        end
      end
    end
  end

Update: I modified the original answer a little and it works for me. Here's my modification:

  # within profile.rb
  # create a hash of profile attributes
  def html_to_hash
    %w{interests favorite_music favorite_books favorite_foods}.inject({}) do |hash, property|
      hash[property] = simple_format(h(self.send(property)), :class => 'pbs tl')
      hash
    end    
  end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

摘星┃星的人 2024-11-10 16:17:03

使该巨大散列中的数据成为 Profile 的方法。

class Profile
  def to_hash
    [:interests, :favorite_music, :favorite_books, :favorite_foods].inject({}) do |h, prop|
      h[prop] = simple_format(h(self.send(:prop)), :class => 'pbs tl')
      h
    end
  end
end

然后

# PUT /users/:user_id/profile/:id
  def update
    if request.xhr?
      profile = current_user.profile

      if params[:profile].blank?
        render :json => { :error => "There was no profile data passed in so your profile could not be saved." }, 
               :status => :unprocessable_entity
      else
        if profile.update_attributes(params[:profile])
          render :json => profile.to_hash,
                 :status => :ok
        else
          render :json => { :error => get_errors_for_class(profile).to_sentence }, 
                 :status => :unprocessable_entity
        end
      end
    end
  end

Make the data in that huge hash a method of Profile.

class Profile
  def to_hash
    [:interests, :favorite_music, :favorite_books, :favorite_foods].inject({}) do |h, prop|
      h[prop] = simple_format(h(self.send(:prop)), :class => 'pbs tl')
      h
    end
  end
end

then

# PUT /users/:user_id/profile/:id
  def update
    if request.xhr?
      profile = current_user.profile

      if params[:profile].blank?
        render :json => { :error => "There was no profile data passed in so your profile could not be saved." }, 
               :status => :unprocessable_entity
      else
        if profile.update_attributes(params[:profile])
          render :json => profile.to_hash,
                 :status => :ok
        else
          render :json => { :error => get_errors_for_class(profile).to_sentence }, 
                 :status => :unprocessable_entity
        end
      end
    end
  end
油饼 2024-11-10 16:17:03

您可以在 Profile 类上创建一个返回相同哈希的 as_json 方法,然后只需执行 render :json =>;个人资料。另一种选择是插入 ActiveModel::Serializers 并告诉它您想要序列化哪些属性以及如何序列化。

You can create an as_json method on your Profile class that returns the same hash and then just do render :json => profile. Another alternative is to plug in ActiveModel::Serializers and tell it which attributes you want to serialize and how.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文