Rails 3 - JSON вложенных моделей не возвращается должным образом - PullRequest
0 голосов
/ 11 февраля 2012

Я пытаюсь настроить фронт javascript, который потребляет JSON из бэкэнда Rails.

Единственная проблема заключается в том, что когда у меня есть вложенные модели в Rails, я не уверен, что JSONвозвращается в правильном формате.

У меня есть сообщение модель и комментарий модель.Сообщение имеет много комментариев.У каждой модели есть поля 'title' и 'content'.

Здесь моя проблема до сих пор ...

1) Когда я посещаю URL: http://localhost:3000/posts.json Я получаю ожидаемый результат:

> [{"content":"My first
> post","created_at":"2012-02-07T18:56:16Z","id":1,"title":"Hello","updated_at":"2012-02-07T18:56:16Z"},{"content":"More
> crap","created_at":"2012-02-07T21:30:51Z","id":2,"title":"My 2nd
> Post","updated_at":"2012-02-07T21:30:51Z"}]

2) Если я введу этот URL: http://localhost:3000/posts/1/comments/4.json, я также получу ожидаемое:

> {"content":"that's
> nice","created_at":"2012-02-07T20:57:16Z","id":4,"post_id":1,"title":"cool","updated_at":"2012-02-07T20:57:16Z"}

3) Но ... если я добавлю URL-адрес, подобный следующему: http://localhost:3000/posts/1/comments.json

, он вернет null.

У меня нет доступа к JSON-версии списка комментариев, связанных с публикацией.

Используя стандартные представления Rails, я могу сделать полный CRUD с вложенностью no.проблема, но нужно ли делать что-то отличное от того, как Rails обычно передает JSON обратно, чтобы использовать его на стороне клиента?


EDIT

Я предполагаю, что вам может понадобиться увидеть код контроллера для контроллера комментариев.Вот оно:

class CommentsController < ApplicationController

  before_filter :get_post  

  respond_to :html, :xml, :json

  def index
    @comments = @post.comments.all    
    respond_with (@comment)    
  end

  def show
    @comment = @post.comments.find(params[:id])

    respond_with(@comment)

  end

  def new
    @comment = @post.comments.build

    respond_with(@comment)
  end

  def edit
    @comment = @post.comments.find(params[:id])
  end

  def create
    @comment = @post.comments.build(params[:comment])

    respond_to do |format|
      if @comment.save
        format.html { redirect_to([@post, @comment], :notice => 'Comment was successfully created.') }
        format.xml  { render :xml => @comment, :status => :created, :location => @comment }
        format.json  { render :json => @comment, :status => :created, :location => @comment }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
        format.json  { render :json => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

 def update
    @comment = @post.comments.find(params[:id])

    respond_to do |format|
      if @comment.update_attributes(params[:comment])
        format.html { redirect_to(@comment, :notice => 'Comment was successfully updated.') }
        format.xml  { head :ok }
        format.json  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
        format.json  { render :json => @comment.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @comment = @post.comments.find(params[:id])
    @comment.destroy

    respond_to do |format|
      format.html { redirect_to(post_comments_url) }
      format.xml  { head :ok }
      format.json  { head :ok }
    end
  end  

  protected  

  def get_post
    @post = Post.find_by_id(params[:post_id])
    redirect_to root_path unless @post
  end

end

1 Ответ

2 голосов
/ 11 февраля 2012
def index
    @comments = @post.comments.all    
    respond_with (@comment)    
end

Вы не назначили @ комментарий.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...