Model as a group that can add other User models - ruby-on-rails

I am having trouble trying to achieve the following, mostly in the controller part:
I have a User model and a Firm model.
A User can create a Firm, this will mean that this user will be the firm owner. Additionally, this user can add other users to join the firm.
So far, my Models are as follows:
class Firm< ActiveRecord::Base
has_many :users, dependent: :destroy
end
class User < ActiveRecord::Base
...
belongs_to :bufete
end
Here is my create action in my firms controller:
def create
#bufete = Bufete.create(bufete_params)
#user = current_user
#bufete.users.create(#user) # Mark that this user belongs to a bufete
#user.owner = true # Mark this user as the owner of the Bufete
respond_to do |format|
if #bufete.save && #user.save
format.html { redirect_to #bufete, :flash => { :success => 'Tu bufete ha sido creado exitosamente.' } }
format.json { render :show, status: :created, location: #bufete }
else
format.html { render 'new', :flash => { :danger => 'Hubo un error al tratar de crear tu bufete.
Porfavor asegurese de que el correo electronico es una direccion valida' } }
format.json { render json: #bufete.errors, status: :unprocessable_entity }
end
end
end
Schema.rb file:
ActiveRecord::Schema.define(version: 20150730061404) do
create_table "bufetes", force: :cascade do |t|
t.string "name"
t.string "address"
t.string "telephone"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "description"
t.string "code"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
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.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "admin", default: false
t.boolean "premium", default: false
t.integer "bufete_id"
t.string "name"
t.string "last_name"
t.boolean "owner", default: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
I believe my associations are correct, but I could be mistaken. My main problem is in the controller. When a user creates a firm, how do I assign this user to be the owner of this Firm? At the same time how do I add this user to the Firm.users collection?
Also, how would I go for adding future users to a specific firm's users collection?
Important: A user can only create ONE Firm. At the same time, a user can only belong to ONE firm as well. If a user creates a firm, it will belong to THAT firm.

I assume Bufete is equal to Firm model, in the code below I'll use Bufete instead of Firm. You can check whether the user can create a new Bufete before creating the Bufete record.
def create
#user = current_user
if #user.can_create_bufete?
#bufete = Bufete.create(bufete_params)
# assign user to #bufete instead of #bufete.users.create()
#user.bufete = #bufete
#user.owner = true
# add your response_to block for #user.saved
else
# add your response_to block of not creating new Bufete
end
end
Then you'll check whether the user can create a Bufete object or not in your User model.
def can_create_bufete?
!owner && !bufete.present? # or any condition that meets your requirement
end

Related

Favorites showing on all users, not the specific one a user favorites

Attempting to make a favorites button, then when clicked will only show favorites for a specific user not show all favorites for all users. My OnClick is hitting my POST correctly, and on the backend when a user favorites a coffee shop it only shows against their profile not anyone else. So I think its just the way im attempting to display this information to the user. I am using React frontend/Rails backend and JWT for Auth.
My Controller
class FavoritesController < ApplicationController
before_action :authorized, only:[:create]
def index
favorite = Favorite.find_by(params[:user_id])
favorites = Favorite.all
render json: favorites
end
def show
favorite = Favorite.find_by(params[:user_id])
render json: favorite
end
....
my onClick ...
....
<button className="submit-fav" onClick={(e) => {this.handleAdd(e)}}> ♥ </button>
...
my fetch to addToFav and show favs
addToFav = (cafe) => {
console.log(cafe)
fetch(`http://localhost:3000/favorites`,{
method: "POST",
headers: {
"Content-Type" : "application/json",
Accept: "application/json",
Authorization: `bearer ${localStorage.token}`
},
body: JSON.stringify( cafe )
})
.then(res => res.json())
.then(json => alert(json.message)
)}
...
componentDidMount() {
fetch(`http://localhost:3000/favorites`)
.then(resp => resp.json())
.then(favorites => this.setState({ favorites }))
}
My Schema
enable_extension "plpgsql"
create_table "coffee_shops", force: :cascade do |t|
t.string "name"
t.string "image_url"
t.string "phone"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "favorites", force: :cascade do |t|
t.integer "user_id"
t.integer "coffee_shop_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "reviews", force: :cascade do |t|
t.string "reviewed_coffee"
t.string "coffee_shop_name"
t.string "user_username"
t.integer "coffee_shop_id"
t.integer "user_id"
t.integer "rating"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "users", force: :cascade do |t|
t.string "city"
t.string "img_url"
t.string "username"
t.string "password_digest"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
end
Any more info needed let me know!
any advise appreciated!
If you're saving favorite correctly and it's a joint table between user and cafe, then your index method is not correct.
First, you have two variables, favorite and favorites. The first one should actually be this, if you use find_by:
favorite = Favorite.find_by(user: params[:user_id])
The other line you have is the following:
favorites = Favorite.all
This queries all the favorites in your database, regardless of who favored them.
So if you want only the favorites that belong to one user you should do:
favorites = Favorite.where(user: params[:user_id])
Now this will only give you the records of the joint table when what you really want is the name and other information of the coffee shops.
So you will need to extend your query to the coffee_shops table and you can do so with a joins statement:
CoffeeShop.joins(:favorites).where(favorites: { user: params[:user_id] })
And this will give you a list of the CoffeeShops that were liked by the user, instead of just the records from the favorites table.

Create action in controller to create an appointment between users and doctors - 204 NO RESPONSE

I'm building an API for an app where a user can make appointments with a doctor.
Everything is working just fine but it's returning 204 - No content when I try to post a new appointment in Postman.
My schema:
create_table "appointments", force: :cascade do |t|
t.date "date"
t.time "time"
t.bigint "user_id"
t.bigint "doctor_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["doctor_id"], name: "index_appointments_on_doctor_id"
t.index ["user_id"], name: "index_appointments_on_user_id"
end
create_table "doctors", force: :cascade do |t|
t.string "name"
t.string "speciality"
t.integer "years_of_experience"
t.integer "likes"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email"
t.string "password_digest"
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_foreign_key "appointments", "doctors"
add_foreign_key "appointments", "users"
end
My appointments controller:
class Api::V1::AppointmentsController < ApplicationController
include CurrentUserConcern
def index
#appointments = Appointment.all
render json: #appointments
end
def create
if #current_user
#appointment = #current_user.appointments.build(appointment_params)
if #appointment.save
render json: #appointment
else
render json: { status: 401 }
end
end
end
private
def appointment_params
params.require(:appointment).permit(:time, :date, #current_user.id, :doctor_id)
end
end
First of all there's not need of sending #current_user.id in appointment_params as user_id will be assigned automatically when this line #appointment = #current_user.appointments.build(appointment_params) execute.
Coming to your issue make sure you are sending a POST request and "body" data in the correct JSON format from PostMan. As per your method appointment_params the request body should look like this
{
appointment: {
time: "",
date: "",
doctor_id:
}
}

Duplicating record and it's children - but children get deleted from old record

My problem is similar to:
My cloning method is stealing the children from the original model
But I can't seem to get the solution for this to work with mine. I'm trying to create an order exchange form which involves populating the form with the old record details. So when I save the form it creates a new Order record but the children seem to get deleted from the old Order record and siphoned into the new one.
Here's the code:
def new
#old_order = Order.includes(:line_items).find(params[:id])
#order = Order.new #old_order.attributes
#order.line_items = []
#old_order.line_items.each do |old|
new = old.dup # the line_item id is set before creation.
new.order_id = #order.id
new.save!
#order.line_items << new
#old_order.line_items << old # this was to see if the old line_items would reappend to the old order. Didn't help...
end
end
def create
#order = Order.new(exchange_order_params)
if #order.save
#order.update_attributes!(stage: 2, ordered_at: Date.today)
redirect_to admin_returns_url, notice: "Order moved to 'accepted' for processing"
else
flash.now[:alert] = "Please try again"
render :action => "new"
end
end
private
def exchange_order_params
params.require(:order).permit(:id, :user_id,
line_items_attributes: [:id, :order_id, :cart_id, :quantity, :_destroy,
product_attributes: [:id, :sku, :euro_price, :sterling_price, :product_group_id, :product_size_id, :product_waistband_id]])
end
Schema.rb
create_table "orders", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "returned", default: false
t.date "date_sent"
t.date "ordered_at"
t.integer "user_id"
t.boolean "return_requested", default: false
t.integer "stage", default: 0
t.decimal "order_total", default: 0.0
t.string "transaction_secret"
t.string "token"
t.string "uuid"
t.string "currency"
t.float "discounted_by", default: 0.0
end
add_index "line_items", ["cart_id"], name: "index_line_items_on_cart_id", using: :btree
add_index "line_items", ["order_id"], name: "index_line_items_on_order_id", using: :btree
add_index "line_items", ["product_id"], name: "index_line_items_on_product_id", using: :btree
create_table "line_items", force: :cascade do |t|
t.integer "quantity"
t.integer "order_id"
t.integer "cart_id"
t.integer "product_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.float "unit_price"
t.string "currency"
end
create_table "product_groups", force: :cascade do |t|
t.string "name"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "product_sizes", force: :cascade do |t|
t.string "specification"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "product_waistbands", force: :cascade do |t|
t.string "specification"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "products", force: :cascade do |t|
t.integer "sku"
t.integer "product_group_id"
t.integer "product_size_id"
t.integer "product_waistband_id"
t.decimal "euro_price"
t.decimal "sterling_price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "stock_level", default: 0
end
add_index "products", ["product_group_id"], name: "index_products_on_product_group_id", using: :btree
add_index "products", ["product_size_id"], name: "index_products_on_product_size_id", using: :btree
add_index "products", ["product_waistband_id"], name: "index_products_on_product_waistband_id", using: :btree
Also in the Order model I am randomising the id before_create so that when the user submits the form, it creates a dupe copy with a different Order id. This is the same for LineItems.
Order.rb (same in LineItem.rb)
before_create :randomize_id
private
def randomize_id
begin
self.id = SecureRandom.random_number(1_000_000)
end while Order.where(id: self.id).exists?
end
My approach would be to override the ActiveRecord::Base#dup method in the Order model so that it's recursive, meaning that it also duplicates the LineItem collection:
class Order < ActiveRecord::Base
def dup
duped_order = super
duped_order.line_items = line_items.map(&:dup)
duped_order
end
end
doing it this way makes it easily testable. Now the controller becomes:
class OrderController < ApplicationController
def new
#order = Order.find(params[:id]).dup
end
def create
# not sure how your form populates the params hash
# here you need to new-up and then save the order and the line items
# with the attributes from the form
end
end
Do write tests to confirm that this is doing what you intend. This is the perfect example of where the old "fat model skinny controller" paradigm should be applied.

ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near "."

I am not sure why my query works on localhost but is failing on the server.
This happens when i try to create a quiz which routes to QuizzesController#new
# GET /quizzes/new
def new
#quiz = current_user.quizzes.new
end
This is the query:
SELECT COUNT(*) FROM "questions" INNER JOIN "question_categories" ON "question_categories"."question_id" = "questions"."id" WHERE "questions"."deleted_at" IS NULL AND (`question_categories`.`category_id` IN (87,1))
(1.0ms) ROLLBACK
Completed 500 Internal Server Error in 58ms (ActiveRecord: 13.4ms)
And i got an error as such.
ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR: syntax error at or near "." LINE 1: ...s"."deleted_at" IS NULL AND (`question_categories`.`category...
quiz.rb
before creating i would run build_parts which should randomly grab questions and place them into quizzes.
class Quiz < ActiveRecord::Base
belongs_to :user
belongs_to :subject
has_many :quiz_categories
has_many :categories, through: :quiz_categories
has_many :quiz_parts
accepts_nested_attributes_for :categories
accepts_nested_attributes_for :quiz_parts
validates :user, :subject, :number_of_questions, presence: true
validates :number_of_questions, numericality: { only_integer: true, greater_than_or_equal_to: 1 }
before_create :build_parts
before_save :set_completed_at, if: -> { completeness == 100.00 }
def completeness
answerable_quiz_parts = 0
quiz_parts.each do |q_part|
answerable_quiz_parts += 1 if q_part.answerable.answers.present?
end
quiz_parts.joins(:choice).count.to_f * 100 / answerable_quiz_parts
end
def score
quiz_parts.joins(:choice).where('choices.correct = ?', true).count { |qp| qp.choice.correct? }
end
private
# select random questions
def build_parts
category_ids = self.categories.map(&:id)
question_pool = Question.joins(:question_categories).where('`question_categories`.`category_id` IN (?)', category_ids)
#self.number_of_questions = [number_of_questions, question_pool.size].min
puts question_pool.size
if number_of_questions > question_pool.size
errors.add(:number_of_questions, 'is too high. Please select a lower question count or increase category selections')
return false
end
number_of_questions.times do |i|
question_pool.inspect
self.quiz_parts << question_pool[i].quiz_parts.new
question_pool[i].question_parts.each do |question_part|
self.quiz_parts << question_part.quiz_parts.new
end
end
end
def set_completed_at
self.completed_at = Time.zone.now
end
end
quizzes_controller.rb
class QuizzesController < ApplicationController
before_action :authenticate_user!
before_action :set_quiz, only: [:show, :edit, :update, :destroy]
# GET /quizzes
# GET /quizzes.json
def index
#quizzes = current_user.quizzes.order(created_at: :desc)
end
# GET /quizzes/1
# GET /quizzes/1.json
def show
end
# GET /quizzes/new
def new
#quiz = current_user.quizzes.new
end
# GET /quizzes/1/edit
def edit
end
# POST /quizzes
# POST /quizzes.json
def create
#quiz = current_user.quizzes.new(quiz_create_params)
respond_to do |format|
if #quiz.save
format.html { redirect_to edit_quiz_path(#quiz), notice: 'Quiz was successfully created.' }
format.json { render :show, status: :created, location: #quiz }
else
format.html { render :new }
format.json { render json: #quiz.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /quizzes/1
# PATCH/PUT /quizzes/1.json
def update
respond_to do |format|
if #quiz.update(quiz_update_params)
format.html { redirect_to #quiz, notice: 'Quiz was successfully updated.' }
format.json { render :show, status: :ok, location: #quiz }
else
format.html { render :edit }
format.json { render json: #quiz.errors, status: :unprocessable_entity }
end
end
end
# DELETE /quizzes/1
# DELETE /quizzes/1.json
def destroy
#quiz.destroy
respond_to do |format|
format.html { redirect_to quizzes_url, notice: 'Quiz was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_quiz
#quiz = current_user.quizzes.find(params[:id])
end
# For quiz setup
def quiz_create_params
params.require(:quiz).permit(:subject_id, :number_of_questions, category_ids: [])
end
# For quiz answering
def quiz_update_params
params.require(:quiz).permit(quiz_parts_attributes: [:id, choice_attributes: [:id, :content, :answer_id, :_destroy]])
end
end
schema.rb:
ActiveRecord::Schema.define(version: 20150726180000) do
create_table "admins", force: :cascade do |t|
t.string "email"
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
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.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "admins", ["confirmation_token"], name: "index_admins_on_confirmation_token", unique: true
add_index "admins", ["email"], name: "index_admins_on_email", unique: true
add_index "admins", ["reset_password_token"], name: "index_admins_on_reset_password_token", unique: true
create_table "answers", force: :cascade do |t|
t.integer "number"
t.text "content"
t.boolean "correct", default: false, null: false
t.integer "answerable_id"
t.string "answerable_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "answers", ["answerable_type", "answerable_id"], name: "index_answers_on_answerable_type_and_answerable_id"
create_table "categories", force: :cascade do |t|
t.string "name"
t.integer "subject_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "categories", ["category_id"], name: "index_categories_on_category_id"
add_index "categories", ["subject_id"], name: "index_categories_on_subject_id"
create_table "choices", force: :cascade do |t|
t.string "content"
t.integer "quiz_part_id"
t.integer "answer_id"
t.boolean "correct"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "choices", ["answer_id"], name: "index_choices_on_answer_id"
add_index "choices", ["quiz_part_id"], name: "index_choices_on_quiz_part_id"
create_table "ckeditor_assets", force: :cascade do |t|
t.string "data_file_name", null: false
t.string "data_content_type"
t.integer "data_file_size"
t.integer "assetable_id"
t.string "assetable_type", limit: 30
t.string "type", limit: 30
t.integer "width"
t.integer "height"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "ckeditor_assets", ["assetable_type", "assetable_id"], name: "idx_ckeditor_assetable"
add_index "ckeditor_assets", ["assetable_type", "type", "assetable_id"], name: "idx_ckeditor_assetable_type"
create_table "levels", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "question_categories", force: :cascade do |t|
t.integer "question_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "question_categories", ["category_id"], name: "index_question_categories_on_category_id"
add_index "question_categories", ["question_id"], name: "index_question_categories_on_question_id"
create_table "question_parts", force: :cascade do |t|
t.text "content"
t.string "type"
t.integer "question_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "deleted_at"
end
add_index "question_parts", ["deleted_at"], name: "index_question_parts_on_deleted_at"
add_index "question_parts", ["question_id"], name: "index_question_parts_on_question_id"
create_table "questions", force: :cascade do |t|
t.text "content"
t.string "type"
t.integer "level_id"
t.integer "subject_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "deleted_at"
t.string "source"
end
add_index "questions", ["deleted_at"], name: "index_questions_on_deleted_at"
add_index "questions", ["level_id"], name: "index_questions_on_level_id"
add_index "questions", ["subject_id"], name: "index_questions_on_subject_id"
create_table "quiz_categories", force: :cascade do |t|
t.integer "category_id"
t.integer "quiz_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "quiz_categories", ["category_id"], name: "index_quiz_categories_on_category_id"
add_index "quiz_categories", ["quiz_id"], name: "index_quiz_categories_on_quiz_id"
create_table "quiz_parts", force: :cascade do |t|
t.integer "quiz_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "answerable_id"
t.string "answerable_type"
end
add_index "quiz_parts", ["answerable_type", "answerable_id"], name: "index_quiz_parts_on_answerable_type_and_answerable_id"
add_index "quiz_parts", ["quiz_id"], name: "index_quiz_parts_on_quiz_id"
create_table "quizzes", force: :cascade do |t|
t.integer "user_id"
t.datetime "completed_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "subject_id"
t.integer "number_of_questions"
end
add_index "quizzes", ["subject_id"], name: "index_quizzes_on_subject_id"
add_index "quizzes", ["user_id"], name: "index_quizzes_on_user_id"
create_table "subjects", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
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.datetime "created_at"
t.datetime "updated_at"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
I believe you are using wrong quotes:
SELECT COUNT(*) ....... (`question_categories`.`category_id` IN (87,1))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Use " " instead of ``
Update:
Yep, I have been right in your quiz model you're using wrong quotes:
def build_parts
category_ids = self.categories.map(&:id)
question_pool = Question.joins(:question_categories).where('`question_categories`.`category_id` IN (?)', category_ids)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Fix it to:
def build_parts
category_ids = self.categories.map(&:id)
question_pool = Question.joins(:question_categories).where('"question_categories"."category_id" IN (?)', category_ids)
^^^^^^^^^^^^^^^^^^^^^

Rails 3 Nested Form; UnknownAttributeError on New

Rails 3.1, Ruby 1.87 (don't hate me). I watched the Railscasts on Nested Forms; I only put that in so you can point out where I might have missed something in the Railscasts if you know them.
Note: I added #sample_data_set.build_sample_data_template but got "unknown attribute: sample_data_set_id" on the post instead [the code is also posted with the new below).
Using a Nested form on Create/New; hit Submit and get:
ActiveRecord::UnknownAttributeError (unknown attribute:
sample_data_templates):
app/controllers/sample_data_sets_controller.rb:50:in new'
app/controllers/sample_data_sets_controller.rb:50:increate'
Sample Data Set Model:
class SampleDataSet < ActiveRecord::Base
has_one :sample_data_template, :dependent => :destroy
accepts_nested_attributes_for :sample_data_template
end
Sample Data Template Model:
class SampleDataTemplate < ActiveRecord::Base
belongs_to :sample_data_set
#Random info generation
def self.name_gen(*prepend)
character_map = [('a'..'z'),('A'..'Z')].map{|i| i.to_a}.flatten
name = (0..8).map{ character_map[rand(character_map.length)] }.join
if prepend[0].nil? || prepend[0] == ""
return name
else
return prepend[0].to_s + "_" + name
end
end
def self.ssn_gen
#broke this out as its own method in case someone wants some logic later one
ssn = ""
3.times do
ssn = ssn + (100..999).to_a.choice.to_s
end
return ssn
end
def self.row_gen(row_count)
#data_rows = Array.new
i = 0
until i > row_count do
#row = SampleDataSet.first
#row.officialFirstName = SampleDataTemplate.name_gen
#row.officialLastName = SampleDataTemplate.name_gen
#row.emailAddresses = #row.officialFirstName + #row.officialLastName + "#aaa.aaa.edu"
#row.ssn = SampleDataTemplate.ssn_gen
#data_rows << #row
i += 1
end
return #data_rows
end
end
Sample Data Controller#New
def new
#sample_data_set = SampleDataSet.new
#sample_data_set.build_sample_data_template #after adding this I get error:unknown attribute: sample_data_set_id
respond_to do |format|
format.html # new.html.erb
format.json { render :json => #sample_data_set }
end
Sample Data Controller#Create
def create
#sample_data_set = SampleDataSet.new(params[:sample_data_set])
respond_to do |format|
if #sample_data_set.save
format.html { redirect_to #sample_data_set, :notice => 'Sample data set was successfully created.' }
format.json { render :json => #sample_data_set, :status => :created, :location => #sample_data_set }
else
format.html { render :action => "new" }
format.json { render :json => #sample_data_set.errors, :status => :unprocessable_entity }
end
end
end
end
Update, added form piece
<div class="sample_fields">
<%= f.fields_for :sample_data_templates do |builder| %>
<%= render "sample_data", :f => builder%>
<% end %>
</div>
Update, Schema:
ActiveRecord::Schema.define(:version => 20120103172936) do
create_table "sample_data_sets", :force => true do |t|
t.string "title"
t.text "description"
t.string "created_for"
t.string "created_by"
t.integer "number_of_records"
t.integer "sample_data_template_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "sample_data_templates", :force => true do |t|
t.integer "sample_data_set_id"
t.string "irn"
t.string "ssn"
t.string "officialLastName"
t.string "officialFirstName"
t.string "emailAddresses"
t.string "campusNum"
t.string "internationalId"
t.string "internationalIdCountry"
t.string "gender"
t.string "officialMiddleInitial"
t.string "previousLastName"
t.string "previousFirstName"
t.string "previousMiddleInitial"
t.string "addressLine1"
t.string "addressLine2"
t.string "addressLine3"
t.string "city"
t.string "state"
t.string "zipCode"
t.string "province"
t.string "homeAreaCode"
t.string "homePhoneNumber"
t.string "homePhoneExtenstion"
t.string "homePhoneCountryCode"
t.string "workAreaCode"
t.string "workPhoneNumber"
t.string "workExtenstion"
t.string "workPhoneCountryCode"
t.string "faxAreaCode"
t.string "faxPhoneNumber"
t.string "faxExtension"
t.string "faxCountryCode"
t.string "race"
t.string "previousDegree"
t.string "region"
t.string "foreignTranscript"
t.string "apolloEmployee"
t.string "nursingLicenseExpiration"
t.string "nursingInsuranceExpiration"
t.string "otherInsuranceExpiration"
t.string "program"
t.string "version"
t.string "groupId"
t.string "team"
t.string "enrollmentUserId"
t.string "admissionsUserId"
t.string "oldProgram"
t.string "oldVersion"
t.string "galaxyStudentOid"
t.string "suffixOne"
t.string "suffixTwo"
t.string "employeId"
t.string "promoCode"
t.string "revCampusOid"
t.string "FerpaNotes"
t.string "isWavierHigh"
t.string "executingUserId"
t.string "totalDeclaredExtCredits"
t.datetime "insuranceExpireDate"
t.datetime "acknowledgementDate"
t.datetime "scheduledReentryDate"
t.datetime "scheduledStartDate"
t.datetime "dateOfBirth"
t.datetime "enrollAgreeSignDate"
t.boolean "usCitizen"
t.boolean "financialAid"
t.boolean "overrideFlag"
t.datetime "created_at"
t.datetime "updated_at"
end
end
Does sample_data_templates table have a sample_data_set_id column? Perhaps you didn't add it to the migration or did not run the migration?

Resources