Reputation: 434
i'm working with ruby 1.9.2, rails 3.1.3, devise 1.5.3, mysql, my app is about surveys, now all users can see all surveys, but I need that user1 just could see surveys created by user1, now user1 and user2, etc. can see all surveys, the authentication module is done with devise, recognize every user by login, in my database I put user_id as foreign key, or just by alter table tablename add column user_id int(11)not null; but when I tried to create a new survey I get this message: Mysql2::Error: Column 'user_id' cannot be null: 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)
*my controller:*
asurveys_controller.rb
class AsurveysController < ApplicationController # GET /asurveys # GET /asurveys.json
def index @asurveys = current_user.asurveys respond_to do |format| format.html # index.html.erb format.json { render json: @asurveys } end end
@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.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
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgerydef after_sign_in_path_for(resource) stored_location_for(resource) || bienvenido_path end end
my models
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 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._%-]+@([A-Z0-9]+.)+[A-Z]{2,4}$/i, :message => "formato incorrecto" validates_format_of :mail_facturacion_alternativo, :with => /^[A-Z0-9._%-]+@([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
class Asurvey < ActiveRecord::Base #asociacion para que las encuestas puedan ser vistas solo por el usuario que la crea
belongs_to :user #belongs_to :user #belongs_to :user, :class_name => "User", :foreign_key => 'user_id' belongs_to :user #, :foreign_key => "user_id" #attr_accessible :user_id #has_many
:asurveys_users #has_many :users, :through => :asurveys_users
has_many :asurveys_users, :class_name => "User", :through => :asurveys_users #fin asociacion, una encuesta pertenece a solo un
usuario 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 de selección: _destroy. Cuando tenga un valor true (cuando haya sido marcada), el registro será
eliminado al enviar el formulario. #User.find(1).asurveys end
views
Encuesta
Nombre: <%=h @asurvey.name %>
<% for question in @asurvey.questions %>
- <%= h question.content %>
<% end %>
<% for answer in question.answers %>
- <%= h answer.content %>
<% end %><%= link_to "Editar", edit_asurvey_path(@asurvey) %> | <%= link_to "Eliminar", @asurvey, :confirm => 'Estas seguro/a?', :method => :delete %> |
<%= link_to "Ver todas las encuestas", asurveys_path %>
asurvey_helper
module AsurveysHelper end
Upvotes: 1
Views: 320
Reputation: 1099
To create new surveys you should do something like this:
current_user.asurveys.create(params[:assurvey])
To get the surveys created only by the loged user:
@asurveys = current_user.asurveys
Upvotes: 0
Reputation: 5294
After "@asurvey = Asurvey.new(params[:asurvey])", you need set the user before save @asurvey, like:
@asurvey = Asurvey.new(params[:asurvey])
@asurvey.user = current_user
Upvotes: 0