2012-02-15 62 views
0

我正在使用rails 3.2.1,ruby 1..9.2,devise 1.5.3,我的应用程序是一个调查生成器...就像surveymonkey,我有一些问题与协会,因为我用我的模型belongs_to和has_many,我需要一个调查只属于一个用户,但如果我登录为diferents用户,我可以看到所有的调查,我的应用程序不会将调查与用户关联...所有的用户都可以看到所有的调查,你能帮我解决这个问题吗?,在此先感谢,这里是我的代码。关联在rails 3中将调查关联到用户

我的控制器:

class AsurveysController < ApplicationController 
    # GET /asurveys 
    # GET /asurveys.json 
    def index 
    @asurveys = Asurvey.all 

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

    # GET /asurveys/1 
    # GET /asurveys/1.json 
    def show 
    @asurvey = Asurvey.find(params[:id]) 

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

    # GET /asurveys/new 
    # GET /asurveys/new.json 
    #def new 
    #@asurvey = Asurvey.new 
    #3.times { @asurvey.questions.build } 

    #respond_to do |format| 
    # format.html # new.html.erb 
    # format.json { render json: @asurvey } 
    #end 
#end 
    #ejemplo railscast para 3 preguntas y 4 respuestas 
    def new 

    @asurvey = Asurvey.new 
    3.times do 
    question = @asurvey.questions.build 
    4.times { question.answers.build } 
    end 
end 
    # 

    # GET /asurveys/1/edit 
    def edit 
    @asurvey = Asurvey.find(params[:id]) 
    end 

    # POST /asurveys 
    # POST /asurveys.json 
    def create 
    @asurvey = Asurvey.new(params[:asurvey]) 

    respond_to do |format| 
     if @asurvey.save 
     format.html { redirect_to @asurvey, notice: 'Encuesta creada exitosamente.' } 
     format.json { render json: @asurvey, status: :created, location: @asurvey } 
     else 
     format.html { render action: "nueva" } 
     format.json { render json: @asurvey.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PUT /asurveys/1 
    # PUT /asurveys/1.json 
    def update 
    @asurvey = Asurvey.find(params[:id]) 

    respond_to do |format| 
     if @asurvey.update_attributes(params[:asurvey]) 
     format.html { redirect_to @asurvey, notice: 'Encuesta actualizada exitosamente.' } 
     format.json { head :ok } 
     else 
     format.html { render action: "editar" } 
     format.json { render json: @asurvey.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /asurveys/1 
    # DELETE /asurveys/1.json 
    def destroy 
    @asurvey = Asurvey.find(params[:id]) 
    @asurvey.destroy 

    respond_to do |format| 
     format.html { redirect_to asurveys_url } 
     format.json { head :ok } 
    end 
    end 
end 

我的模型:

asurvey.rb

class Asurvey < ActiveRecord::Base 
    belongs_to :user 
    has_many :questions, :dependent => :destroy 
    #:dependent => :destroy para que cuando eliminemos una encuesta se eliminen también todas sus preguntas. 
    accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:content].blank? } , :allow_destroy => true 
    #accepts_nested_attributes_for para poder gestionar las preguntas a través de Survey. Con esto podremos crear, actualizar y 

destruir preguntas cuando actualicemos los atributos de una encuesta。 #el nombre de atributo para la caja deselección:_destroy。 Cuando tenga un valor true(cuando haya sido marcada),el registro seráeliminado al enviar el formulario。 端

question.rb

> class Question < ActiveRecord::Base #survey_id para relacionarlo con 
> la encuesta y un campo de contenido para albergar el texto de la 
> pregunta. 
>  has_many :answers, :dependent => :destroy  accepts_nested_attributes_for :answers, :reject_if => lambda { |a| 
> a[:content].blank? }, :allow_destroy => true  end 

answer.rb

class Answer < ActiveRecord::Base 
    belongs_to :question 
end 

user.rb

>  class User < ActiveRecord::Base 
>  # Include default devise modules. Others available are: 
>  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable 
>  
>  has_many :asurveyse 
>  
>  devise :database_authenticatable, :registerable,:confirmable, 
>    :recoverable, :rememberable, :trackable, :validatable 
>  
>  # Setup accessible (or protected) attributes for your model 
>  attr_accessible :email, :password, :password_confirmation, :remember_me, 
>      :tipo_tarjeta, :numero_tarjeta, :fecha_vencimiento, :nombre_en_tarjeta, 
>      :cvv, :nombre, :apellidos, :mail_facturacion, :mail_facturacion_alternativo, 
>      :nombre_empresa, :pais, :direccion,:codigo_postal, :telefono, :numero_orden_compra 
>      
>      #validacion de presencia de campos, no pueden estar en blanco 
>  #validacion de presencia de campos, no pueden estar en blanco 
>  validates_presence_of :numero_tarjeta, 
>  :message => ": ingrese numero de tarjeta (15 digitos)" 
>  validates_presence_of :nombre_en_tarjeta, 
>  :message => ": ingrese el nombre que aparece en su tarjeta" 
>  #validates_presence_of :fecha_vencimiento, 
>  #:message => ": ingrese fecha de vencimiento de su tarjeta" 
>  validates_presence_of :cvv, 
>  :message => ": ingrese cvv " 
>  #validacion de ingreso de campos "datos personales" 
>  validates_presence_of :nombre, 
>  :message => ": ingrese su nombre" 
>  validates_presence_of :apellidos, 
>  :message => ": ingrese sus apellidos" 
>  validates_presence_of :mail_facturacion, 
>  :message => ": ingrese mail de facturacion" 
>  validates_presence_of :mail_facturacion_alternativo, 
>  :message => ": ingrese mail alternativo de facturacion" 
>  validates_presence_of :nombre_empresa, 
>  :message => ": ingrese nombre de su empresa" 
>  validates_presence_of :direccion, 
>  :message => ": ingrese direccion de su empresa" 
>  validates_presence_of :codigo_postal, 
>  :message => ": ingrese codigo postal" 
>  validates_presence_of :telefono, 
>  :message => ": ingrese telefono de su empresa" 
>  validates_presence_of :numero_orden_compra, 
>  :message => ": ingrese numero de orden de compra" 
>  #largo de campos, formato mail 
>  validates_length_of :numero_tarjeta, :minimum => 16, :allow_blank => true, :message => "El numero debe tener al menos 16 
> digitos de longitud" 
>  validates_length_of :nombre_en_tarjeta, :minimum => 2, :allow_blank => true, :message => "minimo 2 caracteres" 
>  validates_length_of :cvv, :in => 3..4, :allow_blank => true, :message => "(en Mastercard y Visa son los 3 ultimos digitos impresos 
> al dorso de la tarjeta, en American Express son los 4 numeros impresos 
> en el frente de la tarjeta arriba de los ultimos digitos grabados en 
> relieve)" 
>  validates_length_of :nombre, :minimum => 2, :allow_blank => true, :message => "minimo 2 caracteres" 
>  validates_length_of :apellidos, :minimum => 4, :allow_blank => true, :message => "minimo 4 caracteres" 
>  validates_format_of :mail_facturacion, 
>  :with => /^[A-Z0-9._%-][email protected]([A-Z0-9]+\.)+[A-Z]{2,4}$/i, :message => "formato incorrecto" 
>  validates_format_of :mail_facturacion_alternativo, 
>  :with => /^[A-Z0-9._%-][email protected]([A-Z0-9]+\.)+[A-Z]{2,4}$/i, :message => "formato incorrecto en mail alternativo" 
>  validates_length_of :nombre_empresa, :minimum => 4, :allow_blank => true, :message => "minimo 4 caracteres" 
>  validates_length_of :direccion, :minimum => 4, :allow_blank => true, :message => "minimo 4 caracteres" 
>  validates_length_of :codigo_postal, :minimum => 7, :allow_blank => true, :message => "minimo 7 caracteres" 
>  validates_length_of :telefono, :minimum => 7, :allow_blank => true, :message => "minimo 7 caracteres" 
>  validates_length_of :numero_orden_compra, :minimum => 2, :allow_blank => true, :message => "minimo 2 caracteres" 
>  
>  #validates_length_of :password, :minimum => 6, :allow_blank => false      
>      
>  end 
+0

您需要接受一些答案。 – shingara 2012-02-15 13:51:13

回答

1

在你Asurveyscontroller更换

@asurveys = Asurvey.all 

通过类似:

@asurveys = current_user.asurveys 

(这是假设,您可以访问与CURRENT_USER当前登录的用户)

在您可以做的演出动作:

@asurvey = current_user.asurveys.find(params[:id]) 

这将确保即使其他用户恶意发布不属于他调查的ID,他也不会看到它。

其他操作将需要类似的更改。

很多将取决于你如何处理你的用户登录。我没有在你的控制器中选择任何before_filters。你需要在这里添加更多的细节。

在这里完全解释如何处理登录会有点困难。要测试代码,您可以添加如下代码:

current_user = User.find(1) 

假设数据库中存在具有此ID的用户。只需设置一个有效的用户对象,然后看看,如果这工作就像你想要的一样。

+0

谢谢,但不工作...过滤器在我的控制器?旧的故事...我是一个begginer ...请帮助,在此先感谢 – suely 2012-02-15 17:02:10

+0

@ user1121744:您需要处理您的登录某处并将current_user设置为有效状态。通常这是在[filters](http://guides.rubyonrails.org/action_controller_overview.html#filters) – 2012-02-15 17:07:34

+0

@ user1121744完成的:对不起,它是current_user.asurveyse(正如你在用户模型中用'has_many:asurveyse'所定义的那样。因为它看起来好像你使用设计进行身份验证,这应该处理设置current_user(错误消息似乎表明,它的工作原理) – 2012-02-15 17:25:47

0

您需要查看Rails嵌套资源。 This rails cast处理该主题。您也可以参考Rails路由文档的this section

+0

将UserLogin作为嵌套资源处理是有点罕见的(虽然这在技术上是可行的) – 2012-02-15 14:42:31