I am new to Rails and I am trying to get my application running.
My UserMigration.rb file contains:
class UserMigration < ActiveRecord::Migration
def self.up
if (!ActiveRecord::Base.connection.table_exists? :users)
drop_table :users
create_table :users do |t|
t.string :email
t.string :first
t.string :last
t.string :password
t.string :username
t.integer :created_by
t.string :bio #Newly added
t.integer :id #Newly added
t.string :photoURL #Newly added
end
add_index :users, :email
end
if (Models::Persistence::User.count == 0)
Models::Persistence::User.create({:email => 'testuser#my.com',
:username => 'testuser#my.com',
:first => 'Test',
:last => 'User',
:password => 'Test123',
:bio => "User, student",
:id => "1",
:photoURL => "http://link",
:created_by => 1})
And my models User.rb file contains:
module Models
module Persistence
class User < ActiveRecord::Base
validates :bio, :presence => true, length: {minimum: 150}
I am working off an example and I just recently added the three extra fields in the users table (bio, id and photoURL). I keep getting this error when I run my tests with the newly added fields on the db:
undefined method `bio' for #<Models::Persistence::User:0x007f8c04ae6838>
Any pointers on where I could start debugging this from? Thanks!
Related
Rails 5.1
My migration file:
class CreateFwExports < ActiveRecord::Migration[5.1]
def change
create_table :fw_exports, id: :string do |t|
t.string :screen_name, index: true, limit: 16
t.string :full_name, limit: 21
t.string :location_placeholder
t.timestamps
end
end
end
From the fw_exports controller:
def fw_export_params
params.require(:fw_export).permit(:screen_name, :full_name, :location_placeholder)
end
In the fw_export.rb model, I have:
has_one :location
has_many :followers
In the location.rb model, I have:
belongs_to :fw_export
In the follower.rb model, I have:
has_many :followed
In my helper file, I have the following method:
def process_spreadsheet(number_of_rows, spreadsheet, followed_id)
(1..number_of_rows).each do |i|
fw_export_record = FwExport.new(
:screen_name => spreadsheet[i][0],
:full_name => spreadsheet[i][1],
:location_placeholder => spreadsheet[i][2],
)
fw_export_record.save
location = Location.new(
:fw_exports_id => fw_export_record.id
)
location.save
follower = Follower.new(
:followed_id => followed_id,
:fw_exports_id => fw_export_record.id
)
follower.save
end
end
What this method does, is receive a spreadsheet CSV object, and iterates through the data, trying to save each row to the fw_exports table. It also creates entries into the locations and followers tables
There is a locations table, with the following fields:
t.string :fw_exports_id, index: true
t.string :city
t.string :state
t.string :country
and a followers table with the following fields:
t.string :followed_id
t.string :fw_exports_id
t.string :slug, index: true
When I try to import the data, I get the following error:
NoMethodError (undefined method `each' for "0":String):
app/helpers/fw_exports_helper.rb:21:in `block in process_spreadsheet'
app/helpers/fw_exports_helper.rb:20:in `process_spreadsheet'
app/controllers/fw_exports_controller.rb:82:in `process_parsed_spreadsheet'
I verified that all the parameters passed to the process_spreadsheet call are valid.
Any ideas?
I am totally new to ruby. I am trying to make a RESTful service for task tracking application. I researched and found Sinatra better for the job than rails. So I am using Sinatra and ActiveRecord. I am following Up and Running With Sinatra and ActiveRecord. I will be creating the client application in .NET using Restsharp. But this is all about server side.
This is the migration I have created
class CreateTasksPeopleDocumentsAndComments < ActiveRecord::Migration
def self.up
create_table :tasks do |t|
t.string :name
t.string :task_status
t.string :task_type
t.text :description
t.text :analysis
t.text :investigation
t.integer :developer_id
t.integer :reviewer_id
t.date :open_date
t.date :analysis_date
t.date :promotion_date
t.date :review_date
t.date :correction_date
t.date :collection_date
t.date :closed_date
t.date :modified_date
t.date :target_date
end
create_table :people do |t|
t.string :name
t.string :trigram
t.string :state
t.string :level
end
create_table :documents do |t|
t.string :name
t.binary :data
t.string :path
t.integer :task_id
t.integer :developer_id
end
create_table :comments do |t|
t.text :comment
t.datetime :comment_timestamp
t.integer :person_id
t.integer :task_id
t.integer :comment_id
end
end
def self.down
drop_tables :tasks
drop_tables :people
drop_tables :documents
drop_tables :comments
end
end
And the Main App.rb
class Person < ActiveRecord::Base
end
class Developer < Person
has_many :tasks
end
class Reviewer < Person
has_many :tasks
end
class Task < ActiveRecord::Base
belongs_to :developer
belongs_to :reviewer
has_many :documents
end
class Document < ActiveRecord::Base
belongs_to :task
belongs_to :developer
end
class Comment < ActiveRecord::Base
belongs_to :task
has_many :comments
end
get '/' do
"Hola World!"
end
get '/tasks' do
Task.all.to_json
end
get '/people' do
Person.all.to_json
end
get '/person/:id' do
Person.where(["id = ?", params[:id]]).to_json
end
get '/task/:id' do
Task.where(["id = ?", params[:id]]).to_json
end
get '/document/:id' do
Document.where(["id = ?", params[:id]]).to_json
end
get '/task/:id/documents' do
# Task.where(["id = ?", params[:id]]).document.all.to_json
# Document.where(["task_id = ?", params[:id]]).all.to_json
Task.find(params[:id]).documents.all.to_json
end
get '/make' do
person1 = Person.create(
:name => "AEonAX",
:trigram =>"anx",
:state => "Active",
:level => "Master"
)
person2 = Person.create(
:name => "XEonAX",
:trigram =>"xnx",
:state => "Inactive",
:level => "User"
)
person3 = Person.create(
:name => "ZEonAX",
:trigram =>"znx",
:state => "Active",
:level => "User"
)
person4 = Person.create(
:name => "LEonAX",
:trigram =>"lnx",
:state => "Inactive",
:level => "Master"
)
task1 = Task.create(
:name => "IR-000001V0R2000",
:description => "The Very First Incident Report",
:task_status => "Opened",
:task_type => "Internal",
:developer_id => person2.id,
:reviewer_id => person1.id
)
task2 = Task.create(
:name => "IR-000002V0R2000",
:description => "Second Incident Report",
:task_status => "Tech. Anal.",
:task_type => "External",
:developer_id => person2.id,
:reviewer_id => person1.id
)
task3 = Task.create(
:name => "IR-000003V0R2000",
:description => "Another Incident Report",
:task_status => "Under Corr.",
:task_type => "External",
:developer_id => person3.id,
:reviewer_id => person1.id
)
document1 = Document.create(
:name => "FirstDoku",
:path => "\\XEON-NB\Test\FiddlerRoot.cer",
:task_id => task1.id,
:developer_id => task1.developer.id,
:data => Task.all.to_json #SomeBinaryData
)
end
Currently this code only reads data. I have not started writing of data.
Basically the relations are like for a task there will be a developer and reviewer. It will have documents attached to it. It will also have comments.
Comments can be on the task or in reply to a comment.
As you can see I have declared a Person class and derived Developer and Reviewer from it. Is it the right way? Any other suggestions are welcome. Even suggestions to use other frameworks are accepted.
I have the following models:
class Programme < ActiveRecord::Base
has_and_belongs_to_many :nationalities, class_name: 'Nation', join_table: 'nationalities_nations'
has_and_belongs_to_many :destinations, class_name: 'Nation', join_table: 'destinations_nations'
accepts_nested_attributes_for :nationalities
accepts_nested_attributes_for :destinations
end
and
class Nation < ActiveRecord::Base
has_and_belongs_to_many :nationality_programmes, class_name: 'Programme', join_table: 'nationalities_nations'
has_and_belongs_to_many :destination_programmes, class_name: 'Programme', join_table: 'destinations_nations'
accepts_nested_attributes_for :nationality_programmes
accepts_nested_attributes_for :destination_programmes
end
In active admin I have the following configuration which pre-selects any existing stored country references correctly (See screenshot).
ActiveAdmin.register Programme do
permit_params :title,
destinations_ids: [:id],
nationalities_ids: [:id]
form do |f|
f.actions
f.inputs 'Countries / Regions' do
f.input :nationalities, :as => :select, :input_html => {:multiple => true}
f.input :destinations, :as => :select, :input_html => {:multiple => true}
f.input :title
end
f.actions
end
end
However, when I select other countries, the form successfully saves, but the references aren’t stored.
This is my schema:
ActiveRecord::Schema.define(version: 20140522131219) do
create_table "destinations_nations", force: true do |t|
t.integer "programme_id", null: false
t.integer "nation_id", null: false
end
create_table "levels_programmes", force: true do |t|
t.integer "programme_id", null: false
t.integer "level_id", null: false
end
create_table "nationalities_nations", force: true do |t|
t.integer "programme_id", null: false
t.integer "nation_id", null: false
end
create_table "nations", force: true do |t|
t.string "slug", limit: 2
t.string "name"
end
create_table "programmes", force: true do |t|
t.string "title"
end
end
Update: Cross-posted this issue on active_admin#3196 which is now closed, thanks to Gregorio's help.
I made it work by changing
permit_params :title,
destinations_ids: [:id],
nationalities_ids: [:id]
to
permit_params :title,
destination_ids: [],
nationality_ids: []
I am newbie to rails ,
I am using devise from ryan bates video tutorial , and , i am stuck at one point
I have created user , role relationship
and in the sign up page , i need to provide select option group for existing roles ,
in my sign up view page i am writing
<%= collection_select(:user,:roles,Role.find(:all),:id,:name) %>
i dont precisely understand collection_select method , kindly help what i might be doing wrong
my models 1 : user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me , :roles
has_and_belongs_to_many :roles
def role?(role)
return !!self.roles.find_by_name(role.to_s.camelize)
end
end
my model 2 : role.rb
class Role < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :users
end
my user migration file
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, :null => false, :default => ""
t.string :encrypted_password, :null => false, :default => ""
## 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
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.timestamps
end
add_index :users, :email, :unique => true
add_index :users, :reset_password_token, :unique => true
end
end
my role migration file
class CreateRoles < ActiveRecord::Migration
def change
create_table :roles do |t|
t.string :name
t.timestamps
end
end
end
my join table migration file
class UsersHaveAndBelongToManyRoles < ActiveRecord::Migration
def up
create_table :roles_users, :id => false do |t|
t.references :role, :user
end
end
def down
drop_table :roles_users
end
end
the ERROR COMING is
undefined method `each' for "2":String
2 being the id of the role selected
In a has_and_belongs_to_many relationship like you have between User and Role, there is no role_id on the User object.
The second parameter of the collection_select is the attribute you're updating with the selection(s), in your case it's not role_id, it's role_ids and seeing as it's a has_and_belongs_to_many relationship you probably want to allow the user to select multiple options, so try something like this:
<%= collection_select(:user, :role_ids, Role.all, :id, :name, {}, { selected: #user.role_ids, multiple: true }) %>
If you attach it to a form_for on your #user object you can use:
<%= f.collection_select(:role_ids, Role.all, :id, :name, {}, multiple: true) %>
I have two classes in ruby:-
class Role < ActiveRecord::Base
# attr_accessible :title, :body
acts_as_authorization_role :subject_class_name => 'User', :join_table_name => "roles_users"
end
and
class User < ActiveRecord::Base
acts_as_authentic
acts_as_authorization_object :role_class_name => 'Role', :subject_class_name => 'User'
acts_as_authorization_subject :association_name => :roles , :join_table_name => 'roles_users'
has_one:employee_detail ,:foreign_key => "User_id"
end
and migration files are:-
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :username
t.string :email
t.string :crypted_password
t.string :password_salt
t.string :persistence_token
t.timestamps
end
end
end
class CreateRoles < ActiveRecord::Migration
def change
create_table "roles" , :force => true do |t|
t.string :name , :limit => 40
t.string :authorizable_type, :limit => 40
t.integer :authorizable_id
t.timestamps
end
end
end
class RolesUsers < ActiveRecord::Migration
def change
create_table "roles_users", :id => false, :force => true do |t|
t.references :user
t.references :role
end
end
end
i have user id and want to retrieve role id, but not able to query intermediate table. can anyone provide some solution for this. thnks
It's clear that your user is going to have multiple roles
You can define an habtm relation in user for for role and get retrive roles roles like following
class User < ActiveRecord::Base
acts_as_authentic
acts_as_authorization_object :role_class_name => 'Role', :subject_class_name => 'User'
acts_as_authorization_subject :association_name => :roles , :join_table_name => 'roles_users'
has_one:employee_detail ,:foreign_key => "User_id"
has_and_belongs_to_many :roles
end
And retrieve roles for a user like below
user = User.find user_id
user.roles # this will give you roles array
role_ids = user.roles.map { |r| r.id } # if you only want array of ids