Not sure how to delete the associate between 'fly' and 'invoice'. What I've tried so far deletes the fly from the database
<table class="table table-condensed">
<thead>
<tr>
<th>Invoice Flies</th>
</thead>
<tbody>
<% #invoice.flies.each do |fly| %>
<tr>
<td><%= fly.name %></td>
<td><%= link_to "delete", ??????, method: :delete,
data: { confirm: "You sure?" } %></td>
</tr>
<% end %>
</tbody>
</table>
Invoice Model:
class Invoice < ActiveRecord::Base
attr_accessible :active
validates :user_id, presence: true
belongs_to :user
has_many :categorizations
has_many :flies, through: :categorizations
end
Invoice migration:
class CreateInvoices < ActiveRecord::Migration
def change
create_table :invoices do |t|
t.boolean :active
t.integer :user_id
t.timestamps
end
add_index :invoices, :user_id
end
end
Categorization Model:
class Categorization < ActiveRecord::Base
attr_accessible :fly_id, :user_id
belongs_to :invoice
belongs_to :fly
end
Categorization migration:
class CreateCategorizations < ActiveRecord::Migration
def change
create_table :categorizations do |t|
t.integer :user_id
t.integer :fly_id
t.timestamps
add_index :categorizations, :user_id
add_index :categorizations, :fly_id
end
end
end
Fly Model:
class Fly < ActiveRecord::Base
attr_accessible :description, :name
validates :description, :name, presence: true
has_many :categorizations
has_many :invoices, through: :categorizations
end
Fly migration:
class CreateFlies < ActiveRecord::Migration
def change
create_table :flies do |t|
t.string :name
t.string :description
t.timestamps
end
end
end
You can use dependent: :destroy like this:
class Fly
has_many :categorizations, dependent: :destroy
...
end
This will destroy the categorizations related to that Fly.
Also, remember to use Fly.destroy(:id) (DO NOT USE Fly.delete(:id), or it won't remove the categorizations dependent on that Fly)
Related
I'm new to ruby on rails and am trying to set up student grading system.
Each student has many courses.
Each course has many units.
Each students needs a grade for each unit.
Models
class Student < ApplicationRecord
validates :student_id, :name, :group, presence: true
has_many :student_classes
has_many :courses, through: :student_classes
has_many :units, through: :courses
has_many :units, through: :grades
has_many :grades
end
class StudentClass < ApplicationRecord
belongs_to :student
belongs_to :course
end
class Course < ApplicationRecord
has_many :student_classes
has_many :students, through: :student_classes
has_many :units
end
class Unit < ApplicationRecord
belongs_to :course
has_many :students, through: :grades
has_many :grades
end
class Grade < ApplicationRecord
belongs_to :student
belongs_to :unit
end
Migration
class CreateStudents < ActiveRecord::Migration[7.0]
def change
create_table :students do |t|
t.integer :uid
t.string :group
t.integer :student_id
t.string :name
t.string :first_name
t.string :middle_name
t.string :last_name
t.integer :phone
t.string :home_school
t.string :external_email
t.string :usi
t.datetime :dob
t.boolean :lnn_assessment_registered_status
t.boolean :lnn_assessment_completed_status
t.boolean :enrolment_paperwork_completed__status
t.datetime :enrolment_paperwork_completed_date
t.string :enrolled_in_energySpace_userid
t.boolean :teams_group_and_chat_created_and_user_added_status
t.string :Comments
t.datetime :date
t.string :assessor_name
t.string :campus
t.boolean :yes_no_status
t.string :satisfactory
t.string :competency
t.string :course_code
t.string :course_name
t.timestamps
end
class CreateStudentClasses < ActiveRecord::Migration[7.0]
def change
create_table :student_classes do |t|
t.references :student, null: false, foreign_key: true
t.references :course, null: false, foreign_key: true
t.timestamps
end
class CreateCourses < ActiveRecord::Migration[7.0]
def change
create_table :courses do |t|
t.string :course_name
t.string :course_code
t.timestamps
end
class CreateGrades < ActiveRecord::Migration[7.0]
def change
create_table :grades do |t|
t.references :student, null: false, foreign_key: true
t.references :unit, null: false, foreign_key: true
t.boolean :enrolled
t.boolean :cy
t.boolean :awaiting_confirmation
t.boolean :profiling
t.boolean :missed
t.boolean :skills
t.boolean :ukt
t.boolean :waiting_on_staff
t.timestamps
end
class CreateUnits < ActiveRecord::Migration[7.0]
def change
create_table :units do |t|
t.string :unit_name
t.string :unit_code
t.integer :course_id
t.timestamps
end
I am able to view the code with in the course model with
<h1><%= #course.course_name %></h1>
<table>
<tr >
<tr class="student-list-row">
<th>Unit Name</th>
<th>Unit Code</th>
<th>Unit ID</th>
<% #course.units.each do |unit| %>
<tr class="student-list-row">
<td class="student-list-item"><%= unit.unit_name %></td>
<td class="student-list-item"><%= unit.unit_code %></td>
<td class="student-list-item"><%= unit.id %></td>
<td><%= link_to 'Show' %></td>
</tr>
<% end %>
</tr>
</tr>
But I would like to create a table that has all units in a course as the columns, and the students as the rows, with each grade being shown. Is this possible to do with this arrangement?
Is this also able to be achieved whilst viewing all courses/units a student is assigned to?
I have three models: user, firm and revenue. I'd like to join the firm and revenue models, in order to publish the joined model results. Could someone please point me in the right direction on how to go about joining these tables and publish the results? Note, firm and revenue model can be joined through a unique_id number. Here is some of my code:
Revenue Model
class Revenue < ActiveRecord::Base
belongs_to :user
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Revenue.create! row.to_hash
end
end
end
Firm Model
class Firm < ActiveRecord::Base
belongs_to :user
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Firm.create! row.to_hash
end
end
end
User Model
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
before_save { self.email = email.downcase }
has_many :revenues
has_many :firms
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:session_limitable, :confirmable
validates :name, :lastname, :industry, :company, :title, :address, :state, :city, :zip, presence: true
validates :phone, presence: true, length: { maximum: 11 }
end
Revenue DB
class CreateRevenues < ActiveRecord::Migration
def change
create_table :revenues do |t|
t.integer :unique_id
t.integer :revenue
t.integer :profit
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
Firm DB
class CreateFirms < ActiveRecord::Migration
def change
create_table :firms do |t|
t.integer :unique_id
t.string :name
t.string :state
t.string :city
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
View
<h2>Firm Data</h2>
<body>
<table>
<tr>
<th>unique_id</th>
<th>name</th>
<th>state</th>
<th>city</th>
</tr>
<body>
<% #firms.each do |firm| %>
<tr>
<td><%= firm.unique_id %> </td>
<td><%= firm.name %> </td>
<td><%= firm.state %> </td>
<td><%= firm.city %> </td>
<tr>
<% end %>
</table>
</body>
<h2>Revenue Data</h2>
<body>
<table>
<tr>
<th>unique_id</th>
<th>revenue</th>
<th>profit</th>
</tr>
<body>
<% #revenues.each do |rev| %>
<tr>
<td><%= rev.unique_id %> </td>
<td><%= rev.revenue %> </td>
<td><%= rev.profit %> </td>
<tr>
<% end %>
</table>
</body>
As per your question and comments it looks right to me to set up relationships as follow:
A user has_many firms (companies). A firm has_one revenue. A user has_many revenues through firms.
# app/models/user.rb
class User < ActiveRecord::Base
has_many :firms
has_many :revenues, through :firms
end
# app/models/firm.rb
class Firm < ActiveRecord::Base
has_one :revenue
end
# app/models/revenue.rb
class Revenue < ActiveRecord::Base
belongs_to :firm
end
Instead of storing a unique_id in both firms and revenues tables, it would be better to use a foreign_key in revenues, like firm_id.
The corresponding migrations are:
class CreateFirm < ActiveRecord::Migration
def change
create_table :firm do |t|
t.string :name
t.string :state
t.string :city
t.timestamps null: false
end
end
end
class CreateRevenue < ActiveRecord::Migration
def change
create_table :firm do |t|
t.belongs_to :firm, index: true
t.integer :revenue
t.integer :profit
t.timestamps null: false
end
end
end
This will enable you to use, for example, firm.revenue.profit to display the value of profit in the app/views/firms/show.html.erb view.
Looking at your models and migrations syntax it seems you are not using Rails 5. You can find Rails 4.2 docs about the has_one relationship here.
I have many images(add_images_to_steps) belonging to steps which belongs to diys. All information saves correctly as DB browser shows, but i have problem viewing images.
with
views/diys/show.html.erb
<p id="notice"><%= notice %></p>
<h2><%= #diy.summary %></h2>
<% #steps.each do |step| %>
<p><%= step.step_content %></p>
<% step.add_images_to_steps.each do |i| %>
<%= image_tag i.image_url.to_s %>
<% end %>
<% end %>
I get NoMethodError in Diys#Show
undefined method `image_url' for #
and if I change
to
I get this
-----------------------------------------------------------------------
Heres My migrations, models and controllers.
-----------------------------------------------------------------------
diys_controller.rb
class DiysController < ApplicationController
before_action :set_diy, only: [:show, :edit, :update, :destroy]
def show
#diy = Diy.find(params[:id])
#steps = #diy.steps.all
#diy.add_images_to_steps.all
end
def new
#diy = Diy.new
#step = #diy.steps.new
#step.add_images_to_steps.new
end
...
def diy_params
params.require(:diy).permit(:title, :summary, :tip, :warning, steps_attributes: [:step_content, add_images_to_steps_attributes: [:image]])
end
models/diy.rb
class Diy < ActiveRecord::Base
has_many :steps, dependent: :destroy
accepts_nested_attributes_for :steps, reject_if: :all_blank
has_many :add_images_to_steps, :through => :steps, dependent: :destroy
accepts_nested_attributes_for :add_images_to_steps
end
models/step.rb
class Step < ActiveRecord::Base
belongs_to :diy
has_many :add_images_to_steps, dependent: :destroy
accepts_nested_attributes_for :add_images_to_steps
mount_uploader :image, ImageUploader
end
models/add_images_to_step.rb
class AddImagesToStep < ActiveRecord::Base
belongs_to :step
end
Diy migration
class CreateDiys < ActiveRecord::Migration
def change
create_table :diys do |t|
t.string :title
t.text :summary
t.text :tip
t.text :warning
t.timestamps null: false
end
end
end
Steps migration
class CreateSteps < ActiveRecord::Migration
def change
create_table :steps do |t|
t.belongs_to :diy
t.text :step_content
t.timestamps null: false
end
end
end
add_images_to_step migration
class CreateAddImagesToSteps < ActiveRecord::Migration
def change
create_table :add_images_to_steps do |t|
t.belongs_to :step
t.string :image
t.timestamps null: false
end
end
end
I figured it out!!
Had to add
mount_uploader :image, ImageUploader
to ../models/add_images_to_step.rb
change def store_dir to
"#{Rails.root}/public/uploads/"
in ../app/uploaders/image_uploader.rb
and
"<%= image_tag i.image_url.to_s %>"
was right for show view.
I have successfully implemented the dynamic select menus for city and area models in my app.
now I have the following models:
class Pet < ActiveRecord::Base
belongs_to :pet_type
belongs_to :pet_category
belongs_to :pet_breed
end
class PetType < ActiveRecord::Base
has_many :pet_categories, through: :pet_type_categories
has_many :pet_type_categories
end
class PetCategory < ActiveRecord::Base
has_many :pet_types, through: :pet_type_categories
has_one :pet_type_category
end
class PetTypeCategory < ActiveRecord::Base
belongs_to :pet_type
belongs_to :pet_category
has_many :pet_breeds
end
class PetBreed < ActiveRecord::Base
belongs_to :pet_type_category
belongs_to :pet_Type
belongs_to :pet_category
end
migrations:
class CreatePetTypes < ActiveRecord::Migration
def change
create_table :pet_types do |t|
t.string :name
t.timestamps
end
end
end
class CreatePetCategories < ActiveRecord::Migration
def change
create_table :pet_categories do |t|
t.string :name
t.timestamps
end
end
end
class CreatePetTypeCategories < ActiveRecord::Migration
def change
create_table :pet_type_categories do |t|
t.references :pet_type, index: true
t.references :pet_category, index: true
t.timestamps
end
end
end
class CreatePetBreeds < ActiveRecord::Migration
def change
create_table :pet_breeds do |t|
t.string :name
t.references :pet_type_category, index: true
t.timestamps
end
end
end
The pet_type_category table is a join table for pet_types that share the same pet_categories.
So my question is how do I create 3 dynamic select menus of pet_type, pet_category and pet_breed in the create form?
Thanks
Edit: I managed to get the pet type collection_select and pet category grouped_collection_select done once I updated the relationships, now the 3rd one (pet breed) is what I'm stuck at..
I understand now after a bit of a research that it is not possible to have nested groups though surely It should be possible using some kind of helper, however for a lack of a better solution, I added to the PetTypeCategory model:
def pet_type_category_names
"#{self.pet_type.name} #{self.pet_category.name}"
end
and in my view now I have:
<div class="field">
<%= f.collection_select :pet_type_id, PetType.all, :id, :name, {prompt: "Choose your pet's type"} %>
</div>
<div class="field">
<%= f.grouped_collection_select :pet_category_id, PetType.all, :pet_categories, :name, :id, :name, {prompt: "Choose your pet's category"} %>
</div>
<div class="field">
<%= f.grouped_collection_select :pet_breed_id, PetTypeCategory.all, :pet_breeds, :pet_type_category_names, :id, :name, {prompt: "Choose your pet's breed"} %>
</div>
so for the 3rd select instead of having:
Dog
Small
Breed
I have:
Dog Small
Breed
I need (or I think) implement polymorphic association in my model but I have something wrong. Let see my situation, it's a simple question/answers system, and the logic is the following:
- a question can be ansewered by N answers.
- An answer can be only a "text" XOR (one or other, not both) a "picture".
Migrations:
class CreateAnswers < ActiveRecord::Migration
def change
create_table :answers do |t|
t.integer :question_id
t.references :answerable, :polymorphic => true
t.timestamps
end
end
end
class CreateAnswerTexts < ActiveRecord::Migration
def change
create_table :answer_texts do |t|
t.text :content
t.timestamps
end
end
end
class CreateAnswerPictures < ActiveRecord::Migration
def change
create_table :answer_pictures do |t|
t.string :content
t.timestamps
end
end
end
Models
*answer.rb*
class Answer < ActiveRecord::Base
belongs_to :user_id
belongs_to :question_id
belongs_to :answerable, :polymorphic => true
attr_accessible :answerable_type
end
answer_text.rb
class AnswerText < ActiveRecord::Base
TYPE = "text"
has_one :answer, :as => :answerable
attr_accessible :content
end
answer_picture.rb
class AnswerPicture < ActiveRecord::Base
TYPE = "picture"
has_one :answer, :as => :answerable
attr_accessible :content
end
Controller
answers_controller.rb:
...
def create
post = params[:answer]
create_answerable(post[:answerable_type], post[:answerable])
#answer = #answerable.answer.new()
end
private
def create_answerable(type, content)
#answerable = ('Answer' + type.capitalize).classify.constantize.new(:content => content)
#answerable.save
end
...
And view form (Only have these fields):
...
<div class="field">
<%= f.label :answerable_type %><br />
<%= select("answer", "answerable_type", Answer::Types, {:include_blank => true}) %>
</div>
<div class="field">
<%= f.label :answerable %><br />
<%= f.text_field :answerable %>
</div>
...
So, the problem is when I submit form I get this error:
undefined method new' for nil:NilClass
app/controllers/answers_controller.rb:52:increate'
Answers? :)
on a has_one relationship, you have to use :
#answerable.build_answer
or
#answerable.create_answer
instead of
#answerable.answer.new
see the reference for more info.