处理Rails json的正确方法是什么

时间:2015-10-19 21:03:35

标签: ruby-on-rails json

我试图了解在rails中输出json数据的正确方法我有两种方法可以生成json想要知道哪一种是正确的以及为什么:

这是我的代码:

  @feed_items = current_user.feed.paginate(page: params[:page], :per_page => 4)
    @feed1 = current_user.feed    
        @m = @feed_items
         @m1 = array = [] 
          @feed_items.each do |m| 
          @username = User.find(m.user.id)
          @like =FeedLike.where(:user_id => current_user.id, :feed_id => m.id)
          h = {} 
          h["id"] = m.id
          h["u_email"] = @username.email
          h["u_name"] = @username.name
          h["u_id"] = @username.id
          h["avatar_url"] = @username.avatar.url(:medium)
          h["user_id"] = m.user_id
          h["created_at"] = m.created_at
          h["like_count"] = m.like_count
          h["lc"] = @like.count
          h["content"] = m.content
          @comments =Comment.where(:feed_id => m.id)
          h["comment"] = array1 =[]
         @comments.each do |n|
          @username = User.find(n.user.id)
          c ={}
          c["u_email"] = @username.email
          c["u_name"] = @username.name
          c["u_id"] = @username.id
          c["avatar_url"] = @username.avatar.url(:medium)
          c["id"] = n.id
          c["comment"] = n.comment
          c["user_id"] = n.user_id
          c["created_at"] = n.created_at
          array1 << c
         end

          array << h 

          end

    respond_to do |format|
      format.json{ 
    render :json => { :Count => @feed1.count, :feed => @m1}

      }

其他代码是这样的:

      respond_to do |format|   
        format.json{
             render :json => { :Count => @feed1.count, :nilay => @m1,
            :feed =>  @feed_items.as_json(include: {user:  {
                                only: [:id,:name,:email],methods: [:avatar_url]},
                                feed_likes:{only: [:id,:user_id,:feed_id]},
                                comments:{}
                                }) 
          }
         }

           end

0 个答案:

没有答案