in my rails3 app i have a debitnote controller ,model and views created by scaffold.
i show you the migration:
class CreateDebitnotes < ActiveRecord::Migration
def self.up
create_table :debitnotes do |t|
t.string :debit_note_number
t.date :date
t.decimal :amount, :precision =>18, :scale => 2
t.string :debit_account_of
t.string :debit_for
t.text :description
t.timestamps
end
end
def self.down
drop_table :debitnotes
end
end
in my app i want to automatically generate a unique debitnote number when user open new form to create a deb
You may use UUID generator github repo
Related
I am new in Ruby on Rails and I am trying to make a book registration website. Everything works fine except category section. When a user assign a category to his book, my database copies book_categories.id and put it in book.book_categories_id. The website also have a profile page, where you can view user's book(s). My problem is to display a category.name, I searched a lot of similar problems but I have not found the right answer.
Here is my book controller:
before_action :set_book, except: [:index, :new, :create]
before_action :authenticate_user!, except: [:show]
def show
#photos = #book.photos
end
def index
#books = current_user.books
end
def new
#book = current_user.books.build
end
def create
#book = current_user.books.build(books_params)
if #book.save
redirect_to listing_book_path(#book), notice: "Saved."
else
flash[:alert] = "Failed."
render :new
end
end
private
def set_book
#book = Book.find(params[:id])
end
def book_params
params.require(:book).permit(:book_categories_id, :book_name, :summary, :address, :price, :company_name)
end
As long as I understand, I have to allow my controller to have access to my category table but I do not know how. Also, all of my categories store in seed.rb.
This is my BookCategory.rb model:
class BookCategory < ActiveRecord::Base
has_many :books, :foreign_key => :book_categories_id
end
Book.rb model:
class Book < ApplicationRecord
belongs_to :user, :foreign_key => 'user_id'
has_many :photos, dependent: :delete_all
validates :book_name, presence: true
validates :book_categories_id, presence: true
def cover_photo
if self.photos.length > 0
self.photos[0].image.url
else
"default/image-default.jpg"
end
end
end
My schema.rb:
create_table "book_categories", force: :cascade do |t|
t.string "name"
t.string "subcategory"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "book", force: :cascade do |t|
t.string "book_name"
t.text "summary"
t.string "address"
t.decimal "price", precision: 8, scale: 2
t.boolean "active"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.float "latitude"
t.float "longitude"
t.string "company_name"
t.integer "book_categories_id"
t.index ["book_categories_id"], name: "index_books_on_book_categories_id"
end
Usually, when I type #book_categories.name, I get an error:
undefined method `name' for nil:NilClass
And at the very end, it says Parameters: {"id"=>"15"} whereas the category.id is different, and it passes book.id instead.
What I am doing wrong?
First fix the naming problem you have going. I don't know how the books table got called "book" instead of "books" in the schema, but you might have to fix that first.
Then category should be singular everywhere except the database table name. You need to make a migration to fix the foreign key and its index in the books table something like this:
class FixCategoryNaming < ActiveRecord::Migration
def change
remove_column :books, :book_categories_id
add_reference :books, :book_category, index: true, foreign_key: true
end
end
Then run rails db:migrate and check the schema looks ok
Then in the BookCategory class change the line to simply
has_many :books
You need to add this line to your Book class
belongs_to :book_category
and change the validation for book_category to be this
validates :book_category_id, presence: true
Then in the view for book index you have a #books variable. You can get the book name and category name for each book like this:
<% #books.each do |book| %>
<p><%= book.book_name %></p>
<p><%= book.book_categories.name %></p>
<% end %>
I think you need to setup as has_many through relationship. This is a good place to start http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association
I need to implement activeuuid gem to have UUIDs instead of default Rails ids. we can implement it for creating new migration as:
class CreateStudents < ActiveRecord::Migration
def change
create_table :students, :id => false do |t|
t.uuid :id, :primary_key => true
t.string :name
t.string :email
t.timestamps
end
end
end
And in model we include ActiveUUID::UUID as:
class Student < ActiveRecord::Base
attr_accessible :email, :name
include ActiveUUID::UUID
end
Now I already have a database so how can I implement the activeuuid gem to have UUIDs instead of default Rails ids for existing DB?
Need to make changes in all migrations or what?
Need help in this regard. thanks
The UUID is stored as a binary field w/ 16 positions as I found here: https://github.com/jashmenn/activeuuid/blob/master/lib/activeuuid/patches.rb#L62
It worked for me (existing table without records):
def change
reversible do |dir|
change_table :payments do |t|
dir.up { t.change :id, :binary, limit: 16, :primary_key => true }
dir.down { t.change :id, :integer }
end
end
end
Don't forget to add those lines to your model as well:
include ActiveUUID::UUID
natural_key :at_least_one_field_here
More info in the github repo: https://github.com/jashmenn/activeuuid/
Is there a way to specify a database level uniqueness constraint on a field in a Rails 3.1+ migration? I know ActiveRecord's validates_uniqueness_of would work, but I'm curious to know if this can be specified elsewhere.
For example, in order to specify that the 'login' field should be unique in a migration such as ...
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :login
t.timestamps
end
end
end
... I'd like to add an option like :unique => true.
There's nothing mentioned in the Documentation so I assume that's not a great place/way to do things, but does anyone know how this might be achieved (even if it's manually added to the resulting schema)? Or is validates_uniqueness_of the preferred way to go?
You can add unique index so:
def change
create_table :users do |t|
t.string :name
t.string :login
t.timestamps
end
add_index :users, :login, :unique => true
end
when i deal with a migrate data,i want to make each record unique in the table the migrate file make.here is my migrate file:
def self.up
create_table :rbac_mandata do |t|
t.integer :mandator_id
t.integer :mandatarius_id
t.integer :permission_id
t.timestamps
end
add_index :rbac_mandata, [:mandator_id, :mandatarius_id, :permission_id], :unique => true
end
when i execute rake task and find it not work.but when i change it to this,it was done:
def self.up
create_table :rbac_mandata do |t|
t.integer :mandator_id
t.integer :mandatarius_id
t.integer :permission_id
t.timestamps
end
add_index :rbac_mandata, [:mandator_id, :permission_id], :unique => true
end
The generated index name is probably too long, it's probably over 64 characters. Just define the name manually and it'll go through fine, like this...
add_index :rbac_mandata, [:mandator_id, :mandatarius_id, :permission_id], :unique => true, :name => 'my_index_name_here'
How can i give composite primary key in Rails without any gem?
My first table in migration file:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :userid
t.string :name
t.string :address
t.timestamps
end
end
def self.down
drop_table :users
end
end
My second table in migration file:
class CreateProjects < ActiveRecord::Migration
def self.up
create_table :projects do |t|
t.string :title
t.string :description
t.timestamps
end
end
def self.down
drop_table :projects
end
end
In my schema file:
ActiveRecord::Schema.define(:version => 20110222044146) do
create_table "projects", :force => true do |t|
t.string "title"
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", :force => true do |t|
t.string "userid"
t.string "name"
t.string "address"
t.datetime "created_at"
t.datetime "updated_at"
end
end
Now I want to create a table called User_has_project in which I will refer to User and Project that means will have 2 foreign keys.
So I tried like this:
class CreateUser_has_projects < ActiveRecord::Migration
def self.up
create_table :user_has_projects do |t|
t.references :User
t.references :Project
t.boolean :status
t.timestamps
end
end
def self.down
drop_table :users
end
end
Now how can I set combination of user_id and project_id as a primary key in user_has_projects?
It looks like you're trying to specify a many-many relationship between Users and Projects, with an additional field on the relationship itself.
The way you're currently doing isn't the Rails way of doing things - especially with the concept of a composite primary key.
The Rails/ActiveRecord way of doing this sort of relationship modelling is to have a third model that describes the relationship between User and Project. For the sake of example, I'm going to call it an Assignment. All you need to do is re-name your user_has_projects table to assignments like so:
class CreateAssignments < ActiveRecord::Migration
def self.up
create_table :assignments do |t|
t.references :user
t.references :project
t.boolean :status
t.timestamps
end
end
def self.down
drop_table :assignments
end
end
And then, in your model files:
# app/models/user.rb
class User < ActiveRecord::Base
has_many :assignments
has_many :projects, :through => :assignments
end
# app/models/assignment.rb
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
# app/models/project.rb
class Project < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
You can read more about this here: http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association