Created
January 16, 2011 11:40
-
-
Save andresgutgon/781714 to your computer and use it in GitHub Desktop.
Setting relacion has_many :througt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Intervienen en esta función los siguiente modelos | |
1- User | |
2- Profile | |
3- Publication | |
4- ProfilePosition | |
User es donde gestiono la autenticacion. Pero la informacion del miembro la almaceno en Profile. | |
Un Profile tiene muchas publicaciones y una publicacion tiene muchos profiles. Todo a traves de ProfilePosition | |
Estos son los modelos: | |
class User < ActiveRecord::Base | |
# Associations | |
has_one :profile, :class_name => "Profile", :dependent => :destroy | |
has_many :publications # TODO que hacer con las publicaciones creadas por el si el usuario es eliminado | |
... | |
end | |
class Profile < ActiveRecord::Base | |
# Associations | |
belongs_to :user, :class_name => "User" | |
has_many :profile_positions, :dependent => :destroy, :order => "position" | |
has_many :publications, :through => :profile_positions, :include => :profile_positions | |
end | |
class Publication < ActiveRecord::Base | |
#Associations | |
belongs_to :user | |
has_many :profile_positions, :dependent => :destroy, :order => "position" | |
# Soluciones de Guillermo | |
has_many :profiles, :through => :profile_positions | |
end | |
class ProfilePosition < ActiveRecord::Base | |
#Associations | |
belongs_to :profile | |
belongs_to :publication | |
end | |
En el controlador de Publications hago para (por ejemplo) el metodo show una query condicionada si en la URL me viene el ID del User o no. Si no me viene muestro las publicaciones de todos los miembros. Si viene el ID del User es que estoy en un perfil de usuario/autor. | |
Lo hago con un before_filter | |
Codigo: | |
class PublicationsController < ApplicationController | |
before_filter :find_pub_creator | |
def show | |
@publication = @user_publication.find(params[:id]) | |
if @user | |
render :template => "publications/user_show" | |
else | |
#Cosas para el listado general de publications | |
end | |
end | |
private | |
def find_pub_creator | |
if params[:user_id] | |
@user = User.find(params[:user_id]) | |
@user_publication = @user.profile.publications | |
else | |
@user_publication = Publication | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment