I want each student to be able to post multiple messages on my site.
therefore each student has_many :posts
and a post belongs_to :student (one student only)
The thing is I can create a record for a student in rails console but can't assign a post to the student ? I am a bit confused. The student model with the has many does not have the attributes from the belongs to model ?
I have a student.rb model
class Student < ActiveRecord::Base
attr_accessible :first_name, :last_name, :email, :gender, :number, :college, :password, :budget, :picture
mount_uploader :picture, PictureUploader
has_many :posts
end
I have a post.rb model
class Post < ActiveRecord::Base
attr_accessible :message
belongs_to :student
end
this is my schema
ActiveRecord::Schema.define(version: 20130827191617) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "posts", force: true do |t|
t.text "message"
end
create_table "students", force: true do |t|
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "number"
t.string "college"
t.string "password"
t.float "budget"
t.string "picture"
t.datetime "created_at"
t.datetime "updated_at"
end
You should add student_id integer column (it would be better if there was also index on this column) to posts table.
To do this, you can type in console:
bundle exec rails g migration add_student_id_to_posts student:references
Related
I am new to ruby on rails and don't understand how to create and save records using associated tables. I want the controller to take the data create a product record and then create as many property and product properties associated with that product. The property and product property have a one to one relationship. The product can have many properties and product properties.
Properties and product properties are coming in like this:
{"name"=>"color", "value"=>"red"}
{"name"=>"material", "value"=>"cotton"}
My controller works for the creation of the product but I am unsure how to create a loop that will build as may associated product and product properties that come in the array sent from the client.
My controller now:
class SendDataController < ApplicationController
protect_from_forgery with: :null_session
def hi
product = Product.new
product.name = params[:name]
product.upc = params[:upc].to_i
product.available_on = params[:availableon]
product.save
end
end
Below are my models:
class Product < ApplicationRecord
has_many :propertys, dependent: :destroy
has_many :product_propertys, dependent: :destroy
end
class Property < ApplicationRecord
belongs_to :product
has_one :product_property, dependent: :destroy
end
class ProductProperty < ApplicationRecord
belongs_to :property
belongs_to :product
end
Migration:
class CreateProducts < ActiveRecord::Migration[5.2]
def change
create_table :products do |t|
t.string :name
t.string :upc
t.datetime :available_on
t.timestamps
end
end
end
class CreateProductProperties < ActiveRecord::Migration[5.2]
def change
create_table :product_properties do |t|
t.string :value
t.belongs_to :property
t.belongs_to :product
t.timestamps
end
end
end
class CreateProperties < ActiveRecord::Migration[5.2]
def change
create_table :properties do |t|
t.string :name
t.belongs_to :product
t.timestamps
end
end
end
schema:
ActiveRecord::Schema.define(version: 2018_09_22_140824) do
create_table "product_properties", force: :cascade do |t|
t.string "value"
t.integer "property_id"
t.integer "product_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["product_id"], name: "index_product_properties_on_product_id"
t.index ["property_id"], name: "index_product_properties_on_property_id"
end
create_table "products", force: :cascade do |t|
t.string "name"
t.string "upc"
t.datetime "available_on"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "properties", force: :cascade do |t|
t.string "name"
t.integer "product_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["product_id"], name: "index_properties_on_product_id"
end
end
Thanks for any help you can give a new guy!
Your Product Model plurality required, has_many properties & equally has_many product_properties.
Your Property schema will need product_id as an integer. i would avoid using has_one it can get messy, just use has_many or you may require a has_many through
Your ProductProperty Model You'll also need product_id integer & property_id integer adding them as separate migration.
rails db:create add_product_id_to product_properties, product_id:integer
check the migration file product_id that the attribute is in the file
rails db:migrate
Restart server & test in the console.
Once the Models speak, instantiate a Product object, bring it across into Properties & ProductProperties through the respective controllers by setting & in turn making the SendDataController obsolete unless your logic requires this.
I have a single user table with two roles defined using enums and Single Table Inheritance with two matching user sub classes for Staff and Clinician. Because I need a lot of information about clinicians that I don't need about Staff, I've created a clinician_profiles table and am using after_create :create_clinician_profile in the user model to create a stub for the clinician profile.
I am trying to build a page for clinicians to complete their profiles and am having trouble getting the instance variable defined in the controller so it pulls the appropriate clinician's profile into the view to render the form. I am getting the following error. Note that the user's id I'm logged in as is 104.
ActiveRecord::RecordNotFound in ClinicianProfilesController#edit
Couldn't find ClinicianProfile with 'id'=104
I feel like I'm close but don't know what I'm doing wrong. Any help would be greatly appreciated for a rookie!
I'm landing on the page using this link in the header:
<li><%= link_to "Manage My Profile", edit_clinician_profile_path(current_user) %></li>
Here are relevant parts of my user model:
class User < ApplicationRecord
self.inheritance_column = :role
enum role: { Staff: 0, Clinician: 1}
belongs_to :university
has_many :referral_requests
class Staff < User
validates :university_id, presence: true
end
class Clinician < User
has_many :lists
has_many :universities, through: :lists
has_one :clinician_profile
after_create :create_clinician_profile
end
Here's my ClinicianProfile model:
class ClinicianProfile < ApplicationRecord
has_many :clinician_profile_languages
has_many :languages, through: :clinician_profile_languages
has_many :clinician_profile_races
has_many :races, through: :clinician_profile_races
belongs_to :clinician
end
clinician_profiles schema
create_table "clinician_profiles", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "firstname"
t.string "lastname"
t.string "address1"
t.string "address2"
t.string "city"
t.string "state"
t.string "zip"
t.boolean "accepting_patients"
t.integer "rate"
t.string "license_number"
t.string "license_state"
t.string "school"
t.integer "year_graduated"
t.string "accepts_insurance"
t.boolean "sliding_scale"
t.text "bio"
t.boolean "verified"
t.integer "years_licensed"
t.integer "years_of_experience"
t.integer "clinician_id"
end
ClinicianProfilesController
class ClinicianProfilesController < ApplicationController
def edit
#clinician_profile = ClinicianProfile.find(params[:id])
end
def index
end
def show
end
def create
end
end
Here's the beginning of my view (edit.html.erb in /views/clinician_profiles)
<%= form_for(#clinician_profile) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
def edit
#clinician_profile = ClinicianProfile.find(params[:id])
redirect_to :index and return unless #clinician_profile
end
Hello i have to model like;
class CreateLecturers < ActiveRecord::Migration
def change
create_table :lecturers do |t|
t.string :firstname
t.string :lastname
t.string :position
t.string :email
t.timestamps null: false
end
end
end
and here is my second model.
class CreateCurriculums < ActiveRecord::Migration
def change
create_table :curriculums do |t|
t.string :title
t.integer :hours
t.integer :year
t.text :description
t.timestamps null: false
end
end
end
I want migrate to Curriculums to Lecturer. But not with id, with title
how it's can be possible?
So i use rails-admin. When i add some Curriculum i want to choose with dropdown lecturer and when i add some Lecturer i want to choose Curriculum between models .
No matter what, you have to have association between two models. Also do not forget to add curriculum_id to lectures table.
curriculum.rb
has_many :lectures
lecture.rb
belongs_to :curriculum
To add migration
rails g migration add_curriculum_id_to_lectures curriculum_id:integer
I have quite the Problem with my has_many :through association.
The models look like this:
class User < ActiveRecord::Base
has_many :roles
has_many :datasets, through: :roles
has_secure_password
end
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :dataset
end
class Dataset < ActiveRecord::Base
has_many :roles
has_many :users, through: :roles
end
I want to add a record to roles every time a new Dataset is created. It should
be created with the new Dataset, an existing User 'Admin' and the column name of Role should be set to 'Admin'.
I tried everything I found on Stackoverflow but nothing works for me.
My create method in the DatasetController looks this:
def create
#dataset = Dataset.new(dataset_params)
#dataset.save
#user = User.find_by(name: 'Admin')
#dataset.users << #user
##dataset.roles.create(user: #user, dataset: #dataset, name: 'Admin')
respond_with(#dataset)
end
I tried both the << operator and the create method.
the first results in:
ActiveRecord::UnknownAttributeError in DatasetsController#create
unknown attribute: dataset_id
the second in:
ActiveModel::MissingAttributeError in DatasetsController#create
can't write unknown attribute `user_id
Does anyone know why I get these errors?
my schema.rb:
create_table "datasets", force: true do |t|
t.string "name"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "roles", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "name"
t.string "mail"
t.string "password_digest"
t.datetime "created_at"
t.datetime "updated_at"
end
Your Role model needs columns to refer to which User and Dataset it belongs. Without these it has no idea who belongs to who.
So you simply need to create a migration to add these columns:
class AddRefererColumnsToRole < ActiveRecord::Migration
def change
add_column :roles, :user_id, :integer
add_column :roles, :dataset_id, :integer
end
end
I have got the following models,
class City < ActiveRecord::Base
belongs_to :state
belongs_to :country
end
class State < ActiveRecord::Base
belongs_to :country
has_many :cities
end
class Country < ActiveRecord::Base
has_many :states
has_many :cities, :through => :state
end
This is my schema.rb,
create_table "cities", :force => true do |t|
t.string "name"
t.string "state_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "countries", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "states", :force => true do |t|
t.string "name"
t.string "country_id"
t.datetime "created_at"
t.datetime "updated_at"
end
This is my seed data,
country_in = Country.create(name: 'India')
state_ap = country_in.states.create(name: 'Andhra Pradesh')
state_mh = country_in.states.create(name: 'Maharashtra')
city_hyd = state_ap.cities.create(name: 'Hyderabad')
state_ap.cities.create([{name: 'Tirupathi'}, {name: 'Visakhapatnam'}])
state_mh.cities.create([{name: 'Mumbai'}, {name: 'Pune'}, {name: 'Thane'}])
Problem
When I try to find all cities under "India" using
country_in.cities
I get this error : ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :state in model Country
When I try to find which country the city "Hyderabad" is, using
city_hyd.country , I get nil
Why are the links between cities and countries not present?
Are my associations wrong is there something else I missed out on?
The missing link here is the following (see the "Rails Guides for Associations"):
class Country < ActiveRecord::Base
has_many :states
has_many :cities, :through => :states
end
class City < ActiveRecord::Base
belongs_to :state
def country
state ? state.country : nil
end
end
My changes were the following:
has_many :through needs the plural form, not the singular.
If you use belongs_to in City, there needs to be a state_id defined in the table (which would be redundant). So I have replaced it through a getter method. A corresponding setter method is not possible.
I hope that now works for you.