Relacciones a múltiples niveles

29 views
Skip to first unread message

Paco Daza

unread,
Apr 16, 2013, 7:49:34 AM4/16/13
to ror...@googlegroups.com
Buenas!

Estoy empezando con RoR, y tras realizar el tutorial que muestra paso a paso como realizar el clon de Twitter, he decidido comenzar a desarrollar mi propia aplicación.

Basándome en el tutorial anteriormente nombrado, he desarrollado la parte de autenticación de usuarios y posts relaccionados con un usuario.

Ahora empieza mi problema: Tras asociar un Post a un Usuario, quiero asociar a este post comentarios, y a cada comentario una valoración de 0 a 10 con un pequeño texto.

He declarado las relacciones con has_many y belong_to , pero no se como crear un comentario desde el "show" del post.

Por donde debo continuar? Me encuentro perdido entre varios manuales sin sacar nada en claro.
Un saludo!

Miguel Michelsongs

unread,
Apr 16, 2013, 8:16:05 AM4/16/13
to ror...@googlegroups.com
Hola Paco,

basicamente lo que tienes que hacer es instanciar un nuevo comentario desde el post, activerecord te facilita el trabajo, por ejemplo

comemnts controller

def new
  @post = Post.find(params[:post_id])
  @comment =  @post.comments.new
  .....

def create
  @post = Post.find(params[:post_id])
  @comment =  @post.comments.create(params[:comment])
   ......
  


te recomiendo que la ruta la estructures de la siguiente forma


resources :posts do
  resources :comments do
  end
end

asi tendras rutas del tipo

/posts/1/comments/


esto como punto de partida, si tienes mas dudas , escribe por acá

saludos


Atte.
Miguel Michelson Martinez
www.artenlinea.com


2013/4/16 Paco Daza <pdaza...@gmail.com>
--
--
You received this message because you are subscribed to the Google
Groups "ror-es" group.
To post to this group, send email to ror...@googlegroups.com
To unsubscribe from this group, send email to
ror_es+un...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/ror_es?hl=en
Rails no escala.
 
---
You received this message because you are subscribed to the Google Groups "ror-es" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ror_es+un...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Paco Daza

unread,
Apr 17, 2013, 7:38:20 AM4/17/13
to ror...@googlegroups.com
Buenas Miguel! Antes de nada, agradecerte la ayuda.

He modificado mi aplicación tal y como me has recomendado y ahora mismo puedo acceder a los comentarios tal y como me indicaste.

El problema surge ahora, cuando intento crear un comentario desde la vista show del post me da un error de rutas. Creo que está todo correcto: (rake routes)

new_post_comment GET    /posts/:post_id/commnet/new(.:format)      comments#new
edit_post_comment GET    /posts/:post_id/comments/:id/edit(.:format) comments#edit
  post_sensor GET    /posts/:post_id/comments/:id(.:format)      comments#show

Por otra parte, me gustaría tener alguna recomendación de algún libro o tutorial interesante para este proyecto.

Un saludo y de nuevo mil gracias.

Atte.
Paco Daza



You received this message because you are subscribed to a topic in the Google Groups "ror-es" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/ror_es/pyTcfwoj0SA/unsubscribe?hl=en.
To unsubscribe from this group and all its topics, send an email to ror_es+un...@googlegroups.com.

zerobatu

unread,
Apr 17, 2013, 9:00:35 AM4/17/13
to ror...@googlegroups.com

Lo que estas mostrando son las rutas de las vistas en el router deberías tener también los métodos create y update pasados por POST y PUT, envia el código del controlador para verlo

Paco Daza

unread,
Apr 17, 2013, 11:08:46 AM4/17/13
to ror_es
Este es el código que he generado con Scaffold y posteriormente modificado según la recomendación de Miguel.

Gracias de nuevo.


class CommentsController < ApplicationController
 
  before_filter :signed_in_user, only: [:create,:create, :destroy]
  before_filter :correct_user,   only: :destroy
 

  def index       
   
    @comments = Comment.where("Post_id = ?", params[:Post_id])
   
      #Comment.find_by_Post_id(params[:Post_id])

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @comments }
    end
  
  end

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

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @comment }
    end
  end

 
  def new
   
    @post = Post.find(params[:Post_id])
    @comment =  @post.comments.new


    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @comment }
    end
  end

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


 def create
   
    @post = Post.find(params[:Post_id])
    @comment =  @post.Comments.create(params[:Comment])
 
   

    respond_to do |format|
      if @comment.save
        format.html { redirect_to @comment, alert: 'Comment was successfully created.' }
        format.json { render json: @comment, status: :created, location: @comment }
      else
        format.html { render action: "new" }
        format.json { render json: @comment.errors, status: :unprocessable_entity }
      end
    end
  end

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

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

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

    respond_to do |format|
      format.html { redirect_to Comments_url }
      format.json { head :no_content }
    end
  end

  private
 
    def load_Post
      @post = Post.find(params[:Post_id])
    end
     
end

Paco Daza

unread,
Apr 18, 2013, 5:46:49 AM4/18/13
to ror...@googlegroups.com

Buscando entre los numerosos reecursos sobre Ruby on Rails, he descubierto el concepto de Nested Model, que creo, me será muy útil para mi proyecto.

Os dejo el link aquí.

Un saludo y gracias de nuevo.
Reply all
Reply to author
Forward
0 new messages