I have "advices" which belong to a user. Users have many advices.
I try to show each advice's name of the current user in the view which works fine. However I don't know why all others advice's informations are also displayed in the end of the advice's names list (Advice id, name, content, created_at, updated_at, user_id). Thank you for helping.
View :
<% if user_signed_in? %>
<%= current_user.advices.each do |c| %>
<ul>
<li><%= c.name %> - <%= c.content %></li>
</ul>
<% end %>
<% else %>
<p> you have to log in</p>
<% end %>
controller :
def index
#advices = Advice.all
end
Models :
class Advice < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :advices
end
schema :
ActiveRecord::Schema.define(version: 20160329192355) do
create_table "advices", force: :cascade do |t|
t.string "name"
t.text "content"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.boolean "reseau"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.boolean "reseau"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
See this bit?
<%= current_user.advices.each do |c| %>
really should be
<% current_user.advices.each do |c| %>
You've been outputting the array with your advices.
Related
I'm having trouble creating Sign up to my rails app, I'm using Devise and Simple_form, I have 2 models (User and department), users belongs_to :department and department has_many :users, i get an error when i try to sign up saying that department must exits.
devise/registrations/new.html.erb
<h2>Sign up</h2>
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :username, required: true, autofocus: true %>
<%= f.input :email, required: true %>
<%= f.input :password, required: true, hint: ("#{#minimum_password_length} characters minimum" if #minimum_password_length) %>
<%= f.input :password_confirmation, required: true %><br>
<%= f.association :department %>
</div>
<div class="form-actions">
<%= f.button :submit, "Sign up" %>
</div>
<% end %>
<%= render "devise/shared/links" %>
user.rb :
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates_uniqueness_of :email, :username
belongs_to :department
has_and_belongs_to_many :courses
end
department.rb :
class Department < ApplicationRecord
has_many :users
has_many :courses
end
I populated the departments table using seeds.rb and checked through mysql console.
schema.rb :
ActiveRecord::Schema.define(version: 20180502071349) do
create_table "courses", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t|
t.string "name"
t.text "description"
t.bigint "department_id"
t.string "instructor_name"
t.integer "credit_hours"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["department_id"], name: "index_courses_on_department_id"
end
create_table "departments", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "enrollments", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t|
t.bigint "user_id"
t.bigint "courses_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["courses_id"], name: "index_enrollments_on_courses_id"
t.index ["user_id"], name: "index_enrollments_on_user_id"
end
create_table "users", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "username", default: "", null: false
t.bigint "department_id"
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["department_id"], name: "index_users_on_department_id"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
t.index ["username"], name: "index_users_on_username", unique: true
end
add_foreign_key "courses", "departments"
add_foreign_key "enrollments", "courses", column: "courses_id"
add_foreign_key "enrollments", "users"
add_foreign_key "users", "departments"
end
migration files:
class CreateDepartments < ActiveRecord::Migration[5.1]
def change
create_table :departments do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
# frozen_string_literal: true
class DeviseCreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
t.string :username, null: false, default: ""
t.references :department, foreign_key: true
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
add_index :users, :username, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
class CreateCourses < ActiveRecord::Migration[5.1]
def change
create_table :courses do |t|
t.string :name
t.text :description
t.references :department, foreign_key: true
t.string :instructor_name
t.integer :credit_hours
t.timestamps
end
create_table :enrollments do |t|
t.references :user, foreign_key: true
t.references :courses, foreign_key: true
t.timestamps
end
end
end
P.S., I'm just starting out with rails and thanks for your help.
Error screenshot:
Devise doesn't know anything about your none standard department_id field and filters it as unpermitted parameter.
Create your own registrations controller (which extends Devise) and then customize these methods:
def sign_up_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :department_id)
end
This is just a sample. Feel it in with your real field names
Rails since 5.1 or so has a required belongs_to validation with newly generated apps.
You can disable that by:
class User < ApplicationRecord
belongs_to :department, optional: true
end
In this way, you can create users with an empty department first.
I am trying to make an admin page that has a nested form for another model.
I have a Playbook model:
playbook.rb
has_and_belongs_to_many :groups
accepts_nested_attributes_for :groups
my form view
_form.html.haml
<%= form_with(model: playbook, local: true) do |form| %>
...
<%= collection_check_boxes(:group, :group_ids, Group.all, :id, :name) %>
<div class="actions">
<%= form.submit %>
</div>
To explain it more, playbooks can have many groups which are another model and I want to save to the groups_playbooks join table automatically when saving the playbook using what I think would be a nested form. I just dont know how to do the nested form with a collection of checkboxes like my view.
Here is part of schema to help give a better picture:
create_table "groups", force: :cascade do |t|
t.string "name"
t.string "variables"
t.bigint "server_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["server_id"], name: "index_groups_on_server_id"
end
create_table "groups_playbooks", id: false, force: :cascade do |t|
t.bigint "group_id", null: false
t.bigint "playbook_id", null: false
end
create_table "groups_servers", id: false, force: :cascade do |t|
t.bigint "group_id", null: false
t.bigint "server_id", null: false
end
create_table "playbooks", force: :cascade do |t|
t.string "name"
t.string "play"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "description"
end
create_table "playbooks_servers", id: false, force: :cascade do |t|
t.bigint "playbook_id", null: false
t.bigint "server_id", null: false
end
create_table "servers", force: :cascade do |t|
t.string "name"
t.string "ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "group_id"
t.index ["group_id"], name: "index_servers_on_group_id"
end
According to specification you should use playbook instead of groups
<%= collection_check_boxes(:playbook, :group_ids, Group.all, :id, :name) %>
But as you have the form builder you should look on that specification
For your case
<%= form.collection_check_boxes(:group_ids, Group.all, :id, :name) %>
I have a Rails app that is supposed to allow you to create a profile after you sign up and click the "Create user Profile" link. But for some reason the below error shows up instead of my form field page.
EDIT:
Error raised:
undefined method `first_name' for #<Profile id: nil>
Showing /home/ubuntu/workspace/saasapp/app/views/profiles/_form.html.erb:
<div class="form-group">
<%= f.label :first_name %>
<%= f.text_field :first_name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :last_name %>
Please help. I am not sure where I went wrong. I am taking a course on upskillcourses.com and I followed along with the video and I even copied the code and pasted it in to the file just in case the first two times I typed it out by hand was incorrect.
Here is the routes.rb file:
Rails.application.routes.draw do
root to: 'pages#home'
devise_for :users, controllers: { registrations: 'users/registrations' }
resources :users do
resource :profile
end
get 'about', to: 'pages#about'
resources :contacts, only: [:create]
get 'contact-us', to: 'contacts#new', as: 'new_contact'
end
Schema.rb:
ActiveRecord::Schema.define(version: 20170314180155) do
create_table "contacts", force: :cascade do |t|
t.string "name"
t.string "email"
t.text "comments"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "plans", force: :cascade do |t|
t.string "name"
t.decimal "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "profiles", force: :cascade do |t|
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "plan_id"
t.string "stripe_customer_token"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
end
Looks like your Profile model doesn't have first_name field. Since you didn't get the "migration" error, I can only assume you need to add those 2 fields in a separate migration as a task in your online course...
As per OP's comments:
# Add missing columns to profiles table
rails generate migration AddFirstNameAndLastNameToProfile first_name last_name
# Run migration
rails db:migrate
Have a recipient and sender, both of the same class(Message) for a messaging system in rails. Want to set the params for both i.e. if user creates a message sender by default is the user_id and recipient will be the contact selected from the users contact list.
Currently the database is only receiving a user_id to the recipient_id column which is wrong and should be to sender_id column. Sender_id receives nothing.
After reading, some say not to amend the params as this is bad practice. So set a hidden field in the message view (like the body and title) yet this isn't pushing in to the database.
Two questions, is this process an appropriate rails practice? (ask this as new to rails) If not: can you advise another path or direction? If so: any ideas/thoughts why this isn't saving in to the database?
user model
class User < ActiveRecord::Base
has_many :messages, class_name: "Message", foreign_key: "recipient_id"
has_many :sent_messages, class_name: "Message", foreign_key: "sender_id"
has_many :contacts, dependent: :destroy
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates_presence_of :firstname, allow_blank: false
validates_presence_of :surname, allow_blank: false
end
message model
class Message < ActiveRecord::Base
belongs_to :sender, class_name: "User", foreign_key: "sender_id"
belongs_to :recipient, class_name: "User", foreign_key: "recipient_id"
validates_presence_of :body, :title
end
Messages controller
class MessagesController < ApplicationController
before_action :message, only: [:show]
before_action :authenticate_user!
def index
#messages = current_user.messages
end
def new
#message = Message.new
end
def create
current_user.messages.create(message_params)
redirect_to '/messages'
end
def show
end
private
def message_params
params.require(:message).permit(:title, :body, :sender_id, :recipient_id)
end
def message
#message = Message.find(params[:id])
end
end
message/new view
<%= form_for #message do |f| %>
<%= hidden_field_tag :sender_id, current_user.id %>
<%= f.text_field :title %>
<%= f.text_field :body %>
<%= f.submit %>
<% end %>
schema
ActiveRecord::Schema.define(version: 20160517131719) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "contacts", force: :cascade do |t|
t.string "firstname"
t.string "surname"
t.string "email"
t.integer "phone"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.integer "user_id"
end
add_index "contacts", ["user_id"], name: "index_contacts_on_user_id", using: :btree
create_table "messages", force: :cascade do |t|
t.string "title"
t.text "body"
t.integer "sender_id"
t.integer "recipient_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "firstname"
t.string "surname"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
add_foreign_key "contacts", "users"
end
Try changing your form to this:
<%= form_for #message do |f| %>
<%= f.hidden_field :sender_id, value: current_user.id %>
<%= f.text_field :title %>
<%= f.text_field :body %>
<%= f.submit %>
<% end %>
Currently the database is only receiving a user_id to the recipient_id
column which is wrong and should be to sender_id column.
In your create action, you have current_user.messages.create(message_params). This creates a message record in the DB with the foreign key's(i.e, recipient_id in your case) value with the parent's(user) id. This is the reason, the recipient_id gets the value of user's id.
Sender_id receives nothing.
This is because the hidden_field set for sender_id is not wrapped with the form builder instance. You need to change
<%= hidden_field_tag :sender_id, current_user.id %>
to
<%= f.hidden_field :sender_id, current_user.id %>
I keep getting this exception: "SQLite3::SQLException: no such column: books.user_id: SELECT "books".* FROM "books" WHERE ("books".user_id = 4)". Which sounds like there is no user_id in the books table.
So I just installed the Foreigner plugin and added "t.integer :user_id, :null => false" and "add_foreign_key(:books, :users)" in the book migration file. I ran "rake db:migrate", but still it is giving me the same exception.
I am using Rails 3 in Windows and Devise to authenticate user.
HOME VIEW
<p><%= link_to "Add new Book",:controller =>"book", :action => 'new' %></p>
<% #books.each do |b| %>
<p><%= b.author%></p>
<p><%= b.title%></p>
<%end%>
HOME CONTROLLER
class HomeController < ApplicationController
def index
#user = current_user
#user.books||=Book.new
#books=#user.books
end
end
BOOK CONTROLLER
class BookController < ApplicationController
def new
#books = Book.new
# redirect_to :controller=>"home" ,:action=>"index"
end
def create
#books = Book.new(params[:book])
if #books.save
render "home/index"
#redirect_to :controller=>"home" ,:action=>"index"
else
render :action => 'new'
end
end
CREATE TABLE/BOOK MIGRATION
class CreateBooks < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.text :title
t.text :author
t.integer :user_id, :null => false
t.timestamps
end
add_foreign_key(:books, :users)
end
BOOK VIEW
<h1>Book#new</h1>
<%= form_for(:book) do |f| %>
<p><%= f.text_field :title %></p>
<p><%= f.text_field :author %></p>
<p><%= f.submit "Add book"%>
BOOK MODEL
class Book < ActiveRecord::Base
belongs_to :user
end
USER MODEL
class User < ActiveRecord::Base
has_many :books
# Include default devise modules. Others available are:
# :token_authenticatable, :lockable, :timeoutable and :activatable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation,:firstname,:lastname,:school,:major,:sex,:zipcode
end
ROUTE
Campus::Application.routes.draw do
get "book/index"
get "book/edit"
get "book/new"
get "home/edit"
devise_for :users
resources :book
root :to=> "home#index"
match '/book/new' =>"home#index"
end
DATABASE SCHEMA
ActiveRecord::Schema.define(:version => 20110609055608) do
create_table "books", :force => true do |t|
t.text "title"
t.text "author"
t.integer "user_id", :null => false
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "courses", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "strong_ins", :force => true do |t|
t.string "subject"
t.string "topic"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :limit => 128, :default => "", :null => false
t.string "password_salt", :default => "", :null => false
t.string "reset_password_token"
t.string "remember_token"
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "firstname"
t.string "lastname"
t.text "school"
t.text "major"
t.string "sex"
t.integer "zipcode"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true
create_table "weak_ins", :force => true do |t|
t.string "subject"
t.string "topic"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
end
end
The user_id column should appear in the schema after running the migration. It's not in your listing, so I'd say that's the problem. Make sure rake db:migrate is completing without errors. You can redo the migration with rake db:rollback && rake db:migrate, if necessary.