NoMethodError in ConnectionController#index - ruby-on-rails

When I access localhost:3000,
my browser told error of NoMethodError in ConnectionController#index.
Also,I was told that undefined method `action' for ConnectionController(Table doesn't exist):Class.
The error browser told connection_controller.rb of 26 line was wrong but I didn't write codes so long like 26 lines.
send(name, *arguments, &block)
else
super
end
end
I wrote ,in connection_controller.rb
class ConnectionController < ActiveRecord::Base
def index
personal = {'name'=>'Yamada','old'=>28}
render :json => personal
end
end
in routes.rb,
Rails.application.routes.draw do
namespace :connection do
get '/',action:'index'
end
end
in schema.rb
ActiveRecord::Schema.define(version: 20170101073143) do
create_table "userdata", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
in migrate file ,
class CreateUserdata < ActiveRecord::Migration
def change
create_table :userdata do |t|
t.string :name
t.text :image
t.timestamps null: false
end
end
end
in model,
class Userdatum < ActiveRecord::Base
user = User.new
user.name = "XXX"
user.email = "mail"
user.save
end

Please note that a controller in Rails should extend ActionController class and a Model should extend ActiveRecord::Base class.
You seems to have done this
class ConnectionController < ActiveRecord::Base
end
inside your controller.
It should be
class ConnectionController < ApplicationController
end

Related

How to setup basic Rails models associations?

hey guys im working on a application where a devise user sign ups and logs in, Once the user logs in they can 'create a team' or 'join a team'. I have my associations set up like this
user.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable
validates_presence_of :phone, :city, :state, :street, :zip, presence: true, on: :create
belongs_to :team
end
team.rb
class Team < ApplicationRecord
has_many :users
end
and my tables are set up
schema.rb
create_table "teams", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "team_name"
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.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "firstname"
t.integer "team_id"
t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
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
team_controller.rb
class TeamController < ApplicationController
before_action :authenticate_user!
def index
#team = current_user.team
end
def new_team
end
def create_team
#team = current_user.create_team(sanitize_team)
if #team.save
redirect_to team_root_path
else
render json: #team.errors.full_messages
end
end
def join_team
#teams = Team.all
end
def team
end
private
def sanitize_team
params.require(:team).permit(:team_name, :team_statement)
end
end
I want the users 'team_id' attribute to update with the teams id when they create a team. or when they join a team. Are my associations correct? how would i make this happen in the controller ?
Yes, associations are correct. You can do it better only by adding foreign key to your database schema. It can be done by generator rails g migration AddTeamToUsers team:references
More information about associations can be found here: https://guides.rubyonrails.org/association_basics.html
In controller you have to change only the whitelisting params to allow team_id. And you probably need to add to your form in view something like this:
<%= f.select :team_id, Team.all.map { |t| [t.team_name, t.id] } %>
Let's strip your code example down to the minimum required:
# app/models/team.rb
class Team < ApplicationRecord
has_many :users
end
# app/models/user.rb
class User < ApplicationRecord
belongs_to :team
end
# db/migrate/20181124230131_create_teams.rb
class CreateTeams < ActiveRecord::Migration[5.2]
def change
create_table :teams do |t|
t.string :team_name
t.timestamps
end
end
end
# db/migrate/20181124230136_create_users.rb
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.belongs_to :team
t.timestamps
end
end
end
Then in your controller:
team = Team.where(team_name: 'foo').first_or_create!
team.users << current_user
Start by setting the association up as optional:
class User < ApplicationController
belongs_to :team, optional: true
end
Otherwise the validations on the user model will not let the user be saved without a team.
Then setup the teams resource:
# config/routes.rb
resources :teams do
post :join
end
post :join creates an additional POST /teams/:team_id/join route.
Then setup the controller:
class TeamsController
# ...
# GET /teams/new
def new
#team = Team.find
end
# POST /teams
def create
#team = Team.new(team_params)
if #team.save
unless current_user.team
current_user.update(team: #team)
end
redirect_to 'somewhere'
else
render :new
end
end
# ...
def join
#team = Team.find(params[:team_id])
if current_user.update(team: #team)
redirect_to #team, notice: 'Team joined'
else
redirect_to #team, error: 'Could not join team'
end
end
#
private
def team_params
params.require(:team).permit(:team_name, :team_statement)
end
end
Note that prefixing your action names is neither needed nor compatible with the "Rails way". Prefixing column names is also largely superfluous.

Rails seed migrate is being stopped with an error ActiveModel::UnknownAttributeError

I've been trying to do rake db:seed which normally works for me but now is failing.
Here is the error and the code.
My error logs:
User.rb:
class User < ApplicationRecord
cattr_accessor :current_user
belongs_to :highschool, optional: true
end
High school migration:
class CreateHighschools < ActiveRecord::Migration[5.0]
def change
create_table :highschools do |t|
t.string :secondaryschool
t.timestamps
end
end
end
High School migration reference to User:
class AddHighschoolRefToUsers < ActiveRecord::Migration[5.0]
def change
add_reference :users, :highschools, foreign_key: true
end
end
Highschool.rb:
class Highschool < ApplicationRecord
has_many :users
end
Highschools_controller.rb:
class HighschoolsController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
def create
#highschool = Highschool.new(highschool_params)
if #highschool.save
render json: #highschool
else
render json: {errors: #highschool.errors.full_messages}
end
end
private
def highschool_params
params.require(:highschool).permit(:secondaryschool)
end
end
Schema.rb:
create_table "highschools", force: :cascade do |t|
t.string "secondaryschool"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
Seeds.rb:
Highschool.destroy_all
special = Highschool.create!(Secondaryschool: "Stuyvesant High School")
special2 = Highschool.create!(Secondaryschool: "Brooklyn Tech")
special3 = Highschool.create!(Secondaryschool: "Bronx Science")
Theres a typo:
special = Highschool.create!(secondaryschool: "Stuyvesant High School")
special2 = Highschool.create!(secondaryschool: "Brooklyn Tech")
special3 = Highschool.create!(secondaryschool: "Bronx Science")

"TypeError: no implicit conversion of nil into String" on HABTM association

I have to deal with this error when I try to associate a record to another one via a HABTM association:
Person.first.communities = Communities.all
Models and migrations:
class CreatePeople < ActiveRecord::Migration
def change
create_table :people do |t|
t.string :name
t.string :email
t.timestamps null: false
end
end
end
class CreateCommunities < ActiveRecord::Migration
def change
create_table :communities do |t|
t.string :name
t.text :description
t.timestamps null: false
end
end
end
class CreateJoinTablePersonCommunity < ActiveRecord::Migration
def change
create_join_table :people, :communities do |t|
# t.index [:person_id, :community_id]
# t.index [:community_id, :person_id]
end
end
end
I use the pg (0.18.4) gem with the Postgres (9.5.2)
Youcan use below code to create relationship.
Person.first.communities << Communities.all
If this not works please check your associations via reflect association method on the model.

ActiveModel::MissingAttributeError in Controller #create

I have a rails application with
1)User Model
class User < ActiveRecord::Base
has_secure_password
has_many :projects
end
2) Project Model
class Project < ActiveRecord::Base
belongs_to :user
end
3) CreateUser in db/migrate
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :password_digest
t.references :projects
t.timestamps null: false
end
end
end
4) CreateProject in db/migrarte
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.string :name
t.string :description
t.references :users
t.timestamps null: false
end
end
end
Now in my Controller, I have a function
def create
#project = Project.new(project_params)
#user = User.find(session[:user_id])
if #project.save
#user.projects << Project.find(#project.id)
redirect_to '/'
else
redirect_to '/project/create'
end
end
But when i call http://localhost:3000/project/new, I receive following error :-
-NoMethodError in ProjectController#create
-undefined method `projects' for # User
with
#user.projects << Project.find(#project.id)
highlighted in the extracted source.
Am I entering the record into has_many relationship correct, or is my syntax wrong?
I ran the following code in the console the server,
user = User.find(1)
user.projects
I received this error message:
NoMethodError: undefined method `projects' for #<User:0x00000001f5b508>
from /home/harshil/.rvm/gems/ruby-2.2.1/gems/activemodel-4.2.4/lib/active_model/attribute_methods.rb:433:in `method_missing'
from /home/harshil/.rvm/gems/ruby-2.2.1/gems/activemodel-4.2.4/lib/active_model/attribute_methods.rb:433:in `method_missing'
Thanks
It seems the CreateUser migration is incorrect. It should not reference the projects. Projects should reference the User, which you have done correctly.
I believe this is confusing ActiveRecord
try removing t.references :projects from the UserCreate migration and try again

How to inherit from another Rails migration?

I have a Rails migration for a simple User model:
class Users < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name, :default => :null
t.float :weight
t.datetime :recorded_at
t.timestamps
end
end
end
I would like to have a second table for the history of the user. It should have the same columns but another name, obviously. Also it should reference the user table.
require_relative '20130718143019_create_history.rb'
class History < Users
def change
create_table :history do |t|
t.references :user
# ...?
end
end
end
How can use inheritence to avoid copying all the migration configuration?
After leaving the keyboard tomatoes fell off my eyes and it was clear how I can set this up:
class Users < ActiveRecord::Migration
def change
create_table :users do |t|
prepare_columns(t)
end
end
protected
def prepare_columns(t)
t.string :name, :default => :null
t.float :weight
t.datetime :recorded_at
t.timestamps
end
end
...
require_relative '20130718143019_create_history.rb'
class History < Users
def change
create_table :history do |t|
t.references :user
prepare_columns(t)
end
end
end

Resources