Ассоциация в рельсах 3 ассоциировать 1 опрос на 1 пользователя - PullRequest
1 голос
/ 29 февраля 2012

Я работаю с ruby ​​1.9.2, rails 3.1.3, devise 1.5.3, mysql, мое приложение связано с опросами, теперь все пользователи могут видеть все опросы, но мне нужно, чтобы user1 просто мог видеть опросы, созданные user1, теперь user1 и user2 и т. д. могут видеть все опросы, модуль аутентификации выполняется с помощью devise, распознавать каждого пользователя по логину, в своей базе данных я помещаю user_id в качестве внешнего ключа или просто путем изменения таблицы tablename добавить столбец user_id int (11 )ненулевой; но когда я пытался создать новый опрос, я получаю это сообщение: Mysql2 :: Ошибка: столбец 'user_id' не может быть пустым: INSERT INTO asurveys (created_at, name, updated_at, user_id) VALUES ('2012-02-29 12:39:34', 'Encuesta Musical', '2012-02-29 12:39:34', NULL) * мой контроллер: *

asurveys_controller.rb

класс AsurveysController

индекс индекса @asurveys = current_user.asurveys ответить | сделать | форматировать | format.html # index.html.erb format.json {рендер json: @asurveys} конец конец

@asurvey = Asurvey.find(params[:id])
#@asurvey = current_user.asurveys.find(params[:id])
#current_user.asurveys = User.find(1)
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 раза
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

# УДАЛИТЬ / asurveys / 1 # УДАЛИТЬ /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

application_controller.rb

класс ApplicationController protect_from_forgery

def after_sign_in_path_for (ресурс) сохраненный_положение_for (ресурс) || bienvenido_path end end

мои модели

    class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  #codigo de asociacion, un usuario puede tener muchas encuestas, esta asociacio se hace para que 1 usuario pueda
  #tener muchas encuestas, pero cada encuesta solo tiene 1 usuario

  #codigo de prueba para asociar encuestas a un solo usuario
  #has_many :asurveys
  has_many :asurveys
  #, :foreign_key => :user_id, :class_name => 'User'
  #fin asociacion

  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 продольной "
validates_length_of: nombre_en_tarjeta,: минимум => 2,: allow_blank => true,: message => "минимум 2 знака"
validates_length_of: cvv,: in => 3..4,: allow_blank => true,: message => "(en Mastercard и Visa son los 3 ultimos digitos impresos Аль Дорсо де ла Тарджета, en American Express, сын с 4 номерами ан эль франция де ла таржета снять)» validates_length_of: nombre,: минимум => 2,: allow_blank => true,: message => "минимум 2 знака" validates_length_of: apellidos,: минимум => 4,: allow_blank => true,: message => "минимум 4 знака" validates_format_of: mail_facturacion, : with => /^[A-Z0-9._%-]+@([A-Z0-9]+.)+[AZ]]2,4 enj$/i,: message => "formato incorrecto " validates_format_of: mail_facturacion_alternativo, : with => /^[A-Z0-9._%-]+@([A-Z0-9]+.)+[AZ]]2,4 enj$/i,: message => "formato incorrecto en mail alternativo " validates_length_of: nombre_empresa,: минимум => 4,: allow_blank => true,: message => "минимум 4 знака" validates_length_of: direccion,: минимум => 4,: allow_blank => true,: message => "минимум 4 знака"
validates_length_of: codigo_postal,: минимум => 7,: allow_blank => true,: message => "минимум 7 символов" validates_length_of: telefono,: минимум => 7,: allow_blank => true,: message => "минимум 7 символов" validates_length_of: figurero_orden_compra,: минимум => 2,: allow_blank => true,: message => "минимум 2 знака"

  #validates_length_of :password, :minimum => 6, :allow_blank => false                     

> конец

класс Asurvey

own_to: пользователь #belongs_to: пользователь #belongs_to: пользователь,: class_name => «Пользователь»,: foreign_key => «user_id» принадлежит_to: user #,: foreign_key => «user_id» #attr_accessible: user_id # has_many

: asurveys_users #has_many: пользователи,: through =>: asurveys_users

has_many: asurveys_users,: class_name => "Пользователь",: through =>: asurveys_users #fin asociacion, una encuesta pertuce solo un

usuario has_many: Вопросы,: зависимый =>: уничтожить #: зависимый => : уничтожить паракляндский приказ об уничтожении тамбьен todas sus preguntas. accepts_nested_attributes_for: вопросы, : reject_if => лямбда {| a | а [: содержание] .blank? },: allow_destroy => true #accepts_nested_attributes_for para poder gestionar las preguntas a través de Survey. Con esto podremos crear, актуализированный у вас degrair preguntas cuando actualicemos los atributos de una encuesta.

НОМБРИЧЕСКИЕ СВОЙСТВА. Cuando tenga un valor true (cuando haya sido marcada), el registro será

Ликвидация окружающей среды. # User.find (1) .asurveys end

вид

Encuesta

Nombre: <% = h @ asurvey.name%>

  1. <% = h question.content%>
  2. <% = h answer.content%>

<% = link_to "Editar", edit_asurvey_path (@asurvey)%> | <% = link_to "Eliminar", @asurvey,: подтвердите => 'Estas seguro / a?',: метод =>: удалите%> |
<% = link_to "Ver todas las encuestas", asurveys_path%>

asurvey_helper

модуль AsurveysHelper end

Ответы [ 2 ]

0 голосов
/ 29 февраля 2012

Чтобы создать новые опросы, вы должны сделать что-то вроде этого:

current_user.asurveys.create(params[:assurvey])

Чтобы получить опросы, созданные только зарегистрированным пользователем:

@asurveys = current_user.asurveys
0 голосов
/ 29 февраля 2012

После "@asurvey = Asurvey.new (params [: asurvey])" вам необходимо установить пользователя перед сохранением @asurvey, например:

@asurvey = Asurvey.new(params[:asurvey])
@asurvey.user = current_user
...