I am trying to set up a messaging system on my app and I had it working, but now ActiveRecord is saving the wrong id for the recipient_id.
Here's where the user.id is loaded as 3 but when the values are inserted the messages's recipient.id is 5:
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 ORDER BY "users"."id"
ASC LIMIT 1
Message Load (0.4ms) SELECT "messages".* FROM "messages" LIMIT 1
User Load (0.6ms) SELECT "users".* FROM "users" LIMIT 1
(0.5ms) BEGIN
SQL (1.3ms) INSERT INTO "messages" ("content", "created_at", "recepient_id", "sender_id",
"subject", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["content", "erferfe"],
["created_at", Wed, 17 Dec 2014 19:15:08 UTC +00:00], ["recepient_id", 5], ["sender_id", 3],
["subject", "erfer"], ["updated_at", Wed, 17 Dec 2014 19:15:08 UTC +00:00]]
(5.4ms) COMMIT
Redirected to http://0.0.0.0:3000/messages
Completed 302 Found in 23ms (ActiveRecord: 9.6ms)
Here's MessagesController#create:
def create
#message = current_user.sent_messages.new(message_params)
#message.recepient_id = User.find_by(params[:id]).id
if #message.save
flash[:notice] = 'Message has been sent.'
redirect_to messages_path
else
render :action => :new
end
end
Here's messages.rb:
class Message < ActiveRecord::Base
belongs_to :sender, class_name: "User", primary_key: "sender_id"
belongs_to :recepient, class_name: "User", primary_key: "recepient_id"
belongs_to :user
This is the routing for the messages:
resources :users do
resources :messages
end
This is the view:
<div class="ui button"><i class="mail icon"></i><%= link_to 'Message', new_user_message_path(#user) %></div>
Message_params:
def message_params
params.require(:message).permit(:subject, :user_id, :content, :recepient_id)
end
User.rb
class User < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :omniauthable,
:recoverable, :rememberable, :trackable, :validatable,
:omniauth_providers => [:facebook, :twitter]
TEMP_EMAIL_PREFIX = 'change#me'
TEMP_EMAIL_REGEX = /\Achange#me/
attr_accessor :login
has_many :projects, class_name: "Project", foreign_key: "creator_id"
has_many :sent_messages, class_name: "Message", foreign_key: "sender_id"
has_many :recieved_messages, class_name: "Message", foreign_key: 'recepient_id'
has_many :messages
has_many :projects, dependent: :destroy
has_many :authentications, :dependent => :destroy
validates :email, presence: true,
uniqueness: true,
format: {
with: /\A[A-Za-z0-9._%+-]+#[A-Za-z0-9\.-]+\.[A-Za-z]+\Z/
}
validates_format_of :email, :without => TEMP_EMAIL_REGEX, on: :update
def downcase_email
self.email = email.downcase
end
def generate_password_reset_token
update_attribute(:password_reset_token, SecureRandom.urlsafe_base64(48))
end
def self.find_for_facebook_oauth(auth)
user = User.where(:provider => auth.provider, :uid => auth.uid).first
unless user
user = User.create(:first_name => auth.extra.raw_info.first_name,
:last_name => auth.extra.raw_info.last_name,
:avatar => auth.info.image,
:provider => auth.provider,
:uid => auth.uid,
:email => auth.info.email,
:password => Devise.friendly_token[0,20]
)
user.confirm!
end
user.save
end
def self.find_for_twitter_oauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.avatar = auth.info.image
user.save
end
end
After code change suggested:
User Load (1.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY "users"."id" ASC
LIMIT 1
Message Load (0.3ms) SELECT "messages".* FROM "messages" LIMIT 1
(0.1ms) BEGIN
SQL (0.4ms) INSERT INTO "messages" ("content", "created_at", "sender_id", "subject", "updated_at")
VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["content", "efvefvf"], ["created_at", Wed, 17 Dec 2014
21:02:48 UTC +00:00], ["sender_id", 2], ["subject", "erfvef"], ["updated_at", Wed, 17 Dec 2014
21:02:48 UTC +00:00]]
(7.2ms) COMMIT
Also when I go /users/:user_id/messages my css and javascript files don't work
I am assuming that this feature is initialized from a User "Profile" page which allows the current session user (sender) to send a message to the profile user (recipient).
First off, in your Message model, you do not need belongs_to :user on the Message model nor do you need has_many :messages on the User model.
Next, you have way over complicated the #create action:
def create
#message = current_user.sent_messages.new(message_params)
#message.recipient_id = params[:user_id]
if #message.save
flash[:notice] = 'Message has been sent.'
redirect_to messages_path
else
render :action => :new
end
end
Now, adjust your message_params. You do not need the user_id (will be provided by current_user) nor do you need the recipient_id (will be provided by the url param).
def message_params
params.require(:message).permit(:subject, :content)
end
Give that a try.
Related
I have a registration form that asks for four things: the user's email, the user's name, their company's name, and a password.
The user model contains the email, name, and password fields
class User < ApplicationRecord
belongs_to :account
attr_accessor :account_attributes
accepts_nested_attributes_for :account
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
The account model contains the company's name.
class Account < ApplicationRecord
has_many :users,
:dependent => :destroy
attr_accessor :name
validates :name, presence: true
end
My registration form looks like (using slim templates):
h2
| Sign up
= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f|
= devise_error_messages!
.field
= f.label :email
br
= f.email_field :email, autofocus: true
.field
= f.label :name, "Your name"
br
= f.text_field :name
= f.fields_for :account_attributes do |a|
.field
= a.label :name, "Your company or organization"
br
= a.text_field :name
.field
= f.label :password
- if #minimum_password_length
em
| (
= #minimum_password_length
| characters minimum)
br
= f.password_field :password, autocomplete: "off"
.field
= f.label :password_confirmation
br
= f.password_field :password_confirmation, autocomplete: "off"
.actions
= f.submit "Sign up"
= render "devise/shared/links"
And lastly, my custom registration controller is:
class RegistrationsController < Devise::RegistrationsController
def new
super
resource.build_account
end
def create
super
resource.account ||= Account.new
resource.account.name = sign_up_params[:account_attributes]["name"]
resource.account.save
end
private
def sign_up_params
params.require(:user).permit(:first_name, :name, :email, :password, :password_confirmation, :account_attributes => [:name])
end
end
The account relation itself persists, but the account NAME does not persist. Looking at the server logs, I can see where the account is persisted but I do not see the name persisting. The strange thing is I can see in the server where it attempts to do the transaction but ultimately doesn't issue any SQL update statement (and doesn't issue a rollback indicating there is no validation error).
SQL (0.2ms) INSERT INTO "accounts" ("created_at", "updated_at") VALUES (?, ?) [["created_at", 2016-10-27 16:39:33 UTC], ["updated_at", 2016-10-27 16:39:33 UTC]]
SQL (0.2ms) INSERT INTO "users" ("name", "account_id", "created_at", "updated_at", "email", "encrypted_password") VALUES (?, ?, ?, ?, ?, ?) [["name", "dsfdsfds"], ["account_id", 32], ["created_at", 2016-10-27 16:39:33 UTC], ["updated_at", 2016-10-27 16:39:33 UTC], ["email", "dsfsdfsdf#fdsfasdfdsfsdfdsc.com"], ["encrypted_password", "$2a$11$pUhS5LGJO2VjPvlPVwj0KO6Ce5Ysr8s4Cu.R4kmsWe7CEayk7t8Fm"]]
(2.2ms) commit transaction
(0.0ms) begin transaction
(0.0ms) commit transaction
(0.0ms) begin transaction
SQL (0.3ms) UPDATE "users" SET "updated_at" = ?, "sign_in_count" = ?, "current_sign_in_at" = ?, "last_sign_in_at" = ?, "current_sign_in_ip" = ?, "last_sign_in_ip" = ? WHERE "users"."id" = ? [["updated_at", 2016-10-27 16:39:33 UTC], ["sign_in_count", 1], ["current_sign_in_at", 2016-10-27 16:39:33 UTC], ["last_sign_in_at", 2016-10-27 16:39:33 UTC], ["current_sign_in_ip", "::1"], ["last_sign_in_ip", "::1"], ["id", 36]]
(0.5ms) commit transaction
Redirected to http://localhost:3000/products
I'm tearing my hair out and I've researched every SO question I could find that's seemingly related. I can do puts sign_up_params[:account_attributes]["name"] in the controller and the name I enter into the form prints back properly, I just can't seem to assign it to the model.
The attr_accessor on the account model is what caused this. By defining an attr_accessor, I was overriding Rails built in attribute accessors for database columns.
Simply removing attr_accessor :name from the Account model fixed this.
I'm building a video marketplace where members can buy videos.
However I'm struggling to create the order so that it has the video_id, member_id and price.
This is my code:
Video model:
has_many :members, through: :orders
has_many :orders
accepts_nested_attributes_for :orders
Member model:
has_many :orders
has_many :videos, through: :orders
accepts_nested_attributes_for :orders
Order model:
attr_accessible :price, :stripe_card_token, :member_id, :video_id
belongs_to :video
belongs_to :member
accepts_nested_attributes_for :video
accepts_nested_attributes_for :member
validates :member_id, presence: true
validates :video_id, presence: true
validates :price, presence: true
attr_accessor :stripe_card_token
def save_with_stripe
video = #video.find_by_id(params[:id])
member = #member.find_by_id(params[:id])
if valid?
#order = Stripe::Charge.create(
amount: video.price,
currency: "gbp",
card: stripe_card_token,
description: member.email
)
save!
end
rescue
errors.add :base, "There was a problem with Stripe"
end
Orders Controller:
def new
#order = Order.new
build_order
end
def create
#order = Order.new(params[:order])
if #order.save_with_stripe
flash[:success] = "Enjoy the video!"
else
render partial: 'shared/buynow'
end
end
def build_order
#order.build_member(
member_id: #member.id,
video_id: #video.id,
price: #video.price,
)
end
I think my issue is somewhere in the "build_order" method, but I've tried various different ways and end up with various different errors.
It works in my console:
[221] pry(main)> Order.create(member_id: "36", video_id: "99", price: "1000")
(0.2ms) BEGIN
SQL (0.6ms) INSERT INTO "orders" ("created_at", "member_id", "price", "stripe_card_token", "updated_at", "video_id") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id" [["created_at", Fri, 18 Oct 2013 14:50:09 UTC +00:00], ["member_id", 36], ["price", 1000], ["stripe_card_token", nil], ["updated_at", Fri, 18 Oct 2013 14:50:09 UTC +00:00], ["video_id", 99]]
(0.5ms) COMMIT
=> #<Order id: 3, video_id: 99, member_id: 36, stripe_card_token: nil, price: 1000, created_at: "2013-10-18 14:50:09", updated_at: "2013-10-18 14:50:09">
Any help on what I'm doing wrong would be greatly appreciated.
Cheers,
Mark
Why are you trying to build a member object through the order? Looks like you already have the member and video, so why not just pass the same hash of values in to the call to new?
e.g.
#order = Order.new(member_id: #member.id, video_id: #video.id, price: #video.price)
I cleaned up my code, it looks much nicer now, but still doesn’t work. It starts to be a pain…
I just can’t save a parent with an existing child in nested form with parent has_many childs :through joinmodel.
In my case a Project has_many contributing Teachers and many contributing Pupils, both are Join-Models to Users. A Project has_many Schools as well.
(May be I should better name the models Teacherize and Pupilize or ProjectTeacher and ProjectPupil.)
As long as all records are new it all works fine. As soon as I want to connect an existing User as new Teacher of a new Project I get the following error:
Couldn't find User with ID=1 for Teacher with ID=
(1 is the correct user ID)
The problem should be somewhere her in my helper to setup empty form fields:
At least I guess so...
module ProjectsHelper
def setup_project(project)
if project.teachers.length <= 0 # usually there is just one teacher, so add one if there isn't one
teacher = project.teachers.build(:role_in_project => 'master')
if user_signed_in?
#teacher = project.teachers.new(:role_in_project => 'master', :user => current_user)
teacher.user = current_user # associate first teacher with current_user
else
#teacher = project.teachers.build
teacher.user = User.new # associate first teacher with a new user instance
end
end
if project.project_schools.length <= 0 # usually there is just one school, so add one if there isn't one
project_school = project.project_schools.build
project_school.school = School.new
end
if project.pupils.length < 3 # There can be up to 3 people, so add a blank fieldset as long as there are less than 3
pupil = project.pupils.build
pupil.user = User.new
end
project
end
end
These are my params received:
{"utf8"=>"✓", "authenticity_token"=>"uCCMk/s3SpDfR7+fXcsCOHPvfvivBQv8pVFVhdh6iro=",
"project"=>{
"teachers_attributes"=>{
"0"=>{
"id"=>"",
"user_attributes"=>{
"id"=>"1",
"gender"=>"male",
"title"=>"",
"firstname"=>"Firstname1",
"name"=>"Lastname1",
"faculty"=>"",
"fon"=>"",
"fax"=>""}
}
},
"id"=>"",
"title"=>"First Project",
"description"=>"This is a foo bar project!",
"presentation_type"=>"experimentell",
"note"=>""
},
"commit"=>"Register Project",
"action"=>"create",
"controller"=>"projects"
}
The case isn’t too abstract; it has to be possible to achieve it.
It’s just to connect a new parent record with an existing child record!
In this article, which is very good, exactly the case is explaint:
http://rubysource.com/complex-rails-forms-with-nested-attributes
# app/helpers/form_helper
module FormHelper
def setup_user(user)
user.address ||= Address.new
(Interest.all - user.interests).each do |interest|
user.interest_users.build(:interest => interest)
end
user.interest_users.sort_by! {|x| x.interest.name }
user/tmp/clean-controllers.md.html
end
end
There the interest is existing and gets connected through a new record in interest_uesers.
Why do I get the error when trying to do the same thing?
project.teachers.build(:user => current_user)
I studied several articles and casts, but none of them connect existing childs.
http://railscasts.com/episodes/196-nested-model-form-revised
http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
Rails 3.1+ Nested Forms Issue: Can't mass-assign protected attributes
Trying to use accepts_nested_attributes_for and has_and_belongs_to_many but the join table is not being populated
Quote: “accepts_nested_fields_for is used to create and modify related objects in a form. It can be used to populate join table, which is kind of what you're trying to do. However, using accepts_nested_fields_for to populate the join table is impossible with a HABTM relationship.”
That’s what I wanna do! Populate the join table!
It starts to be frustrating and I’d be glad to get some help!
My Models
class Project < ActiveRecord::Base
attr_accessible :title, :description, :presentation_type, :note,
:project_schools_attributes, :schools_attributes, :teachers_attributes, :pupils_attributes,
:users_attributes
validates_presence_of :title
validates_presence_of :description
validates_presence_of :presentation_type
has_many :project_schools, :dependent => :destroy
accepts_nested_attributes_for :project_schools
has_many :schools, :through => :project_schools
#accepts_nested_attributes_for :schools, :reject_if => :all_blank
has_many :pupils, :dependent => :destroy
accepts_nested_attributes_for :pupils, :reject_if => :all_blank
has_many :users, :through => :pupils
has_many :teachers, :dependent => :destroy
accepts_nested_attributes_for :teachers, :reject_if => :all_blank
has_many :users, :through => :teachers
#accepts_nested_attributes_for :users, :reject_if => :all_blank
end
class ProjectSchool < ActiveRecord::Base
attr_accessible :role_in_project, :comment,
:school_attributes, :school_id, :project_id
belongs_to :school
accepts_nested_attributes_for :school
belongs_to :project
end
class School < ActiveRecord::Base
attr_accessible :email, :fax, :fon, :name, :place, :street, :type_of_school, :www, :zip
has_many :project_schools
has_many :projects, :through => :project_schools
has_many :users # in real live they are named teachers and pupils but in this case the association goes directly to a user_id, not to teacher/pupil model
validates_presence_of :name, :type_of_school, :street, :place, :zip, :fon
validates :email, :format => { :with => /\A([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create }, :allow_blank => true
end
class Teacher < ActiveRecord::Base
attr_accessible :role_in_project, :user, :user_attributes, :project_id, :user_id
belongs_to :project
belongs_to :user
accepts_nested_attributes_for :user
serialize :role_in_project
end
class Pupil < ActiveRecord::Base
attr_accessible :classname, :user_attributes #, :project_id, :user_id
belongs_to :project
belongs_to :user
accepts_nested_attributes_for :user
end
class User < ActiveRecord::Base
serialize :roles
belongs_to :school
has_many :teachers
has_many :pupils
has_many :projects, :through => :teachers
has_many :projects, :through => :pupils
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :gender, :firstname, :name, :street, :place, :title, :faculty, :assignment,
:classname, :zip, :fon, :fax, :school_id, :roles,
:password, :added_by_user_id, :password_confirmation, :remember_me
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable#, :validatable
after_initialize :init
def init
# the default guest user
self.roles ||= ['default'] #will set the default value only if it's nil
end
end
My controller
class ProjectsController < ApplicationController
require 'axlsx'
before_filter :load_page, only: [:show, :index, :destroy]
def new
#project = Project.new
end
def create
#project = Project.new(params[:project])
respond_to do |format|
if #project.save
sign_in(:user, #project.teachers[0].user) unless user_signed_in?
# TODO: send mail
# save as excel file in dropbox
save_in_dropbox(#project)
format.html { redirect_to #project, notice: t('project.was_created') }
else
logger.debug #project.errors.inspect
format.html { render action: "new" }
end
end
end
end
projects/_form.html.haml
%h1
= t('project.register_headline')
= simple_form_for( setup_project(#project), :html => {:class => 'form-horizontal'} )do |f|
= f.error_notification
#teachers-wrapper.well
%span.jumpanchor#lehrkraft_anchor
%fieldset.form-inputs
= f.simple_fields_for :teachers do |teacher|
= render "teacher_fields", :f => teacher
.school-wrapper.well
%span.jumpanchor#schule_anchor
%h2
Informationen zur Schule
%fieldset.form-inputs
= f.simple_fields_for :project_schools do |project_school|
= render "school_fields", :f => project_school
.project-wrapper.well
%span.jumpanchor#projekt_anchor
%h2
Informationen zum Projekt der Schüler
%fieldset.form-inputs
= f.hidden_field :id
= f.input :title, :input_html => { :class => 'span6' }
= f.input :description, :input_html => { :class => 'span6', rows: 5 }
= f.input :presentation_type, collection: ['theoretisch', 'experimentell'], as: :radio_buttons, :class => 'controls-row', :input_html => { :class => 'inline' }
.clearfix
= f.input :note, :input_html => { :class => 'span6', rows: 3 }
.pupils-wrapper.well
%span.jumpanchor#schuler_anchor
%fieldset.form-inputs
= f.simple_fields_for :pupils do |pupil|
= render "pupil_fields", :f => pupil
projects/_teacher_fields.html.haml
= f.simple_fields_for :user do |user|
=# render "teacher_user_fields", :f => user
%h2
Betreuende Lehrkraft
- if user_signed_in?
= user.input :email, :disabled => true, :input_html => {:class => 'email_validation'}
- else
= user.input :email, :autofocus => true, :input_html => {:class => 'email_validation'}, :hint => 'Dies muß Ihre eigene E-Mailadresse sein!'
.details
=# user.hidden_field :id
= user.input :id
= user.input :gender, collection: [:female, :male]
= user.input :title
= user.input :firstname
= user.input :name
= user.input :faculty
= user.input :fon
= user.input :fax
It is Rails 3.2 with Ruby 1.9.3
Hey I'm struggling a bit with the active admin setup related to my user model. I'm using devise.
When I click on the User tab in active admin I get:
NoMethodError in Admin/users#index
Showing /Users/bweidlich/.rvm/gems/ruby-1.9.3-p286/gems/activeadmin- 0.5.1/app/views/active_admin/resource/index.html.arb where line #1 raised:
undefined method `user_id_contains' for #<MetaSearch::Searches::User:0x007fc0a9831cf8>
Extracted source (around line #1):
1: insert_tag renderer_for(:index)
and when I want to edit one particular user I get:
NoMethodError in Admin/users#edit
Showing /Users/bweidlich/.rvm/gems/ruby-1.9.3-p286/gems/activeadmin-0.5.1/app/views/active_admin/resource/edit.html.arb where line #1 raised:
undefined method `user_id' for #<User:0x007fc0a47d3e28>
Extracted source (around line #1):
1: insert_tag renderer_for(:edit)
Does anyone have an idea where I should look for the error?
As always, any help would be greatly appreciated!
Thanks guys
EDIT:
App user model
class User < ActiveRecord::Base
rolify
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable
attr_accessible :role_ids, :as => :admin
attr_accessible :username, :first_name, :last_name, :email, :password, :password_confirmation, :remember_me, :avatar, :bio, :title, :company,:facebook,:twitter,:pinterest,:linkedin
validates_presence_of :username
validates_uniqueness_of :username, :email, :case_sensitive => false
has_many :events
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
has_many :followed_users, through: :relationships, source: :followed
has_many :comments
has_one :avatar
def update_without_password(params={})
params.delete(:current_password)
super(params)
end
def following?(other_user)
relationships.find_by_followed_id(other_user.id)
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by_followed_id(other_user.id).destroy
end
end
active admin user model:
ActiveAdmin.register User do
form do |f|
f.inputs "User Details" do
f.input :email
f.input :password
f.input :password_confirmation
f.input :superadmin, :label => "Super Administrator"
end
f.buttons
end
create_or_edit = Proc.new {
#user = User.find_or_create_by_id(params[:id])
#user.superadmin = params[:user][:superadmin]
#user.attributes = params[:user].delete_if do |k, v|
(k == "superadmin") ||
(["password", "password_confirmation"].include?(k) && v.empty? && !#user.new_record?)
end
if #user.save
redirect_to :action => :show, :id => #user.id
else
render active_admin_template((#user.new_record? ? 'new' : 'edit') + '.html.erb')
end
}
member_action :create, :method => :post, &create_or_edit
member_action :update, :method => :put, &create_or_edit
end
users table schema
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255)
# encrypted_password :string(255)
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# created_at :datetime
# updated_at :datetime
# username :string(255)
# bio :text
# title :string(255)
# company :string(255)
# facebook :text
# twitter :text
# pinterest :text
# linkedin :text
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
# unconfirmed_email :string(255)
# first_name :string(255)
# last_name :string(255)
# avatar :string(255)
# avatar_id :integer
#
I want to add the current_user.id from devise to another model...
question model:
class Question < ActiveRecord::Base
belongs_to :user
attr_accessible :content
validates :content, :presence => true
end
user model:
class User < ActiveRecord::Base
has_many :questions
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
end
my question migration:
class CreateQuestions < ActiveRecord::Migration
def change
create_table :questions do |t|
t.string :content
t.date :deadline
t.integer :user_id
t.timestamps
end
end
end
In my questions controller:
def create
params[:question][:user_id]=current_user.id
#question = Question.new(params[:question])
if #question.save
redirect_to questions_path, :notice => "Successfully created question."
else
setup_questions
render :index
end
end
When i save the question the current_user.id won't be recorded in my database?
Try this instead:
def create
#question = Question.new(params[:question])
#question.user_id = current_user.id
if #question.save
redirect_to questions_path, :notice => "Successfully created question."
else
setup_questions
render :index
end
end