Çağatay Karahan Çağatay Karahan - 1 month ago 21
Ruby Question

RoR Active Records undefined method

I created 2 models User and Server but when I tried to add a data to Server I cannot get the result that I want. When I tried this on Rails Console I am not getting any errors. This is making my head crazy for 2 days now. Tried lots of things.

user.rb

class User < ApplicationRecord
belongs_to :server
end


User Migration

class CreateUsers < ActiveRecord::Migration[5.0]
def change
create_table :users do |t|
t.integer :channel_id
t.timestamps

end
end
end


server.rb

class Server < ApplicationRecord
has_many :user
end


Server Migration

class CreateServers < ActiveRecord::Migration[5.0]
def change
create_table :servers do |t|
t.string :name
t.timestamps
end
end
end


My Controller:

def alert(args)
@server = Server.where(name: args)
if @server == []
Server.create(name: args)
respond_with :message, text: t('.bildirim_on')
else
end
@user = @server.user.create(channel_id: 215682104)
end


I am getting this error:

Server Load (0.1ms) SELECT "servers".* FROM "servers" WHERE "servers"."name" = ? [["name", "videoyun"]]
Completed in 28ms (ActiveRecord: 0.8ms)
undefined method `user' for #<Server::ActiveRecord_Relation:0x00000004dae158>

Answer Source

That's because @server is an ActiveRecord_Relationship, not a Server instance. You should use Server.find_by(name: args) and check if is .present? before creating it (it will return a Server instance or nil, instead of an ActiveRecord Relationship).

Also you should assign to @server the new one within the if statement.