新手问题 求思路

scuwolf · September 12, 2014 · Last by loveltyoic replied at September 15, 2014 · 1428 hits
class Post < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
        has_many :posts
end

比如有以下数据

user_id user_name 1 hanmeimei 2 lilei

post_id user_id post_key post_value 1 1 key1 value1 2 1 key2 value2

我想请求 /user/1/posts 返回一个 json 如下

{ key1: value1, key2: value2 }

很小白的问题,但是想了很久也不知道怎么解决,求指导思路

看来是还没有入门哦,推荐看一看 ruby on rails 教程,看完肯定懂 ps: render posts: @user.posts.to_json

可以在 User 中定义一个 format 数据的方法(可能有更简单的写法,暂时想不出来,欢迎指正)

class User

  def post_infos
    self.posts.inject({}) { |memo, post| memo.merge!({ post.post_key => post.post_value }) }
  end

end

之后在 controller 里面

render json: @user.post_infos
You need to Sign in before reply, if you don't have an account, please Sign up first.