Ruby on rails - undefined method in show.html.erb - ruby-on-rails

I am trying to display the name of the faculty instead of just the ID.
Everything else works except that part where I try to display the name of the faculty. I get an error saying "undefined method" .
I know I am doing something wrong, but I cannot figure it out at all even though I have been looking at this for hours. I am a completely beginner and I would really appreciate your help.
Thank you.
show.html.erb
<p id="notice"><%= notice %></p>
<!-- notice is a ruby method, and its results comes here inside the tags
used when you want the errow page to show on the next page -->
<p>
<strong>Name:</strong>
<%= #student.name %>
</p>
<p>
<strong>Faculty:</strong>
<%= #student.faculty_id %>
<%= #name.faculty_id %>
</p>
<strong>Grade:</strong>
<%= #student.grade%>
</p>
<%= link_to 'Edit', edit_student_path(#student) %> |
<%= link_to 'Back', students_path %>
student.rb
class Student < ActiveRecord::Base
belongs_to :faculty
end
class Name < ActiveRecord::Base
belongs_to :faculty
end
faculty.rb
class Faculty < ActiveRecord::Base
has_many :student
# belongs_to :faculty
has_many :name
end
This is my students_controler.rb
class StudentsController < ApplicationController
before_action :set_student, only: [:show, :edit, :update, :destroy]
# GET /students
# GET /students.json
def index
#students = Student.all
end
# GET /students/1
# GET /students/1.json
def show
end
# GET /students/new
def new
#student = Student.new
end
# GET /students/1/edit
def edit
end
# POST /students
# POST /students.json
def create
#student = Student.new(student_params)
respond_to do |format|
if #student.save
format.html { redirect_to #student, notice: 'Student was successfully created.' }
format.json { render :show, status: :created, location: #student }
else
format.html { render :new }
format.json { render json: #student.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /students/1
# PATCH/PUT /students/1.json
def update
respond_to do |format|
if #student.update(student_params)
format.html { redirect_to #student, notice: 'Student was successfully updated.' }
format.json { render :show, status: :ok, location: #student }
else
format.html { render :edit }
format.json { render json: #student.errors, status: :unprocessable_entity }
end
end
end
# DELETE /students/1
# DELETE /students/1.json
def destroy
#student.destroy
respond_to do |format|
format.html { redirect_to students_url, notice: 'Student was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_student
#student = Student.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def student_params
params.require(:student).permit(:name, :faculty_id)
end
end
The error is undefined method `faculty_id' for nil:NilClass

I am trying to display the name of the faculty instead of just the ID
Since you're a beginner, let me explain it for you...
--
You're currently calling #student.faculty_id
This is the foreign_key of the #student object -- the identifier which links this student object to the appropriate faculty object.
In short, it means that this attribute is a part of the student schema -- you want one which is part of the faculty schema. Thus, you either need to use delegate to call the name attribute from faculty, or just call it directly:
#student.faculty.name
There are deeper problems with your model associations.
The above is how they should be set up:
#app/models/student.rb
class Student < ActiveRecord::Base
belongs_to :faculty
end
#app/models/faculty.rb
class Faculty < ActiveRecord::Base
has_many :students
end
The above will allow you to call the following:
#app/controllers/students_controller.rb
class StudentsController < ApplicationController
def show
#student = Student.find params[:id]
end
end
#app/views/students/view.html.erb
<%= #student.faculty.name %>
You must remember that Rails works on top of a relational database. This works by allowing you to call related objects by virtue of their foreign key.
I can explain more if required.

<%= #name.faculty_id %> won't work.
In your controller eager load the faculty
def show
#student = Student.includes(:faculty)
end
Either do
<% if #student.faculty.present? %>
<%= #student.faculty.name %>
<% end %>
or you could get the faculty in the controller and assign it to a variable
def show
#student = Student.includes(:faculty)
#faculty = #student.faculty
end
Then you can use that
<% if #faculty.present? %>
<%= #faculty.name %>
<% end %>

Error which I see is
class Faculty < ActiveRecord::Base
has_many :student
# belongs_to :faculty
has_many :name
end
Should be
class Faculty < ActiveRecord::Base
has_many :students
# belongs_to :faculty
has_many :names
end
I don't know your error due to this is or not but has_many is not with singular form

Related

Rails API Controller Update Action -- How to add many-to-many

I have a Rails Api that feeds a Vue front end. I have two main models, Contacts and Outlets, with a many to many relationship via a join table ContactOutlets. I am trying to figure out how in the Contacts controller to add an association to an outlet.
I recognize, I could call the ContactOutlet create action separately, but it seems wasteful if Rails can handle this on the back end. I want vue to call contact#update once.
Contact Model:
class Contact < ApplicationRecord
has_many :contact_outlets
has_many :outlets, through: :contact_outlets
has_many :calls
validates_uniqueness_of :email
validates_uniqueness_of :name
end
Outlet Model:
class Outlet < ApplicationRecord
has_many :contact_outlets
has_many :contacts, through: :contact_outlets
has_many :calls
validates_uniqueness_of :website
end
ContactOutlet:
class ContactOutlet < ApplicationRecord
belongs_to :contact
belongs_to :outlet
validates_uniqueness_of :contact_id, :scope => :outlet_id
end
Contacts Controller:
class ContactsController < ApplicationController
before_action :set_contact, only: %i[ show update destroy ]
# GET /contacts
def index
#contacts = Contact.all
render json: #contacts, include: :outlets
end
# GET /contacts/1
def show
render json: #contact, include: :outlets
end
# POST /contacts
def create
#contact = Contact.new(contact_params)
if #contact.save
render json: #contact, status: :created, location: #contact
else
render json: #contact.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /contacts/1
def update
if #contact.update(contact_params)
render json: #contact, include: :outlets
else
render json: #contact.errors, status: :unprocessable_entity
end
end
# DELETE /contacts/1
def destroy
#contact.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_contact
#contact = Contact.find(params[:id])
end
# Only allow a list of trusted parameters through.
def contact_params
params.require(:contact).permit(:name, :email, :bio, :image_url)
end
end
Solved this. In case anyone else is looking the models above are fine. made some adjustments to the contact_params to allow access to the outlets array. Then fixed the update action. Full controller code below:
class ContactsController < ApplicationController
before_action :set_contact, only: %i[ show update destroy ]
# GET /contacts
def index
#contacts = Contact.all
render json: #contacts, include: :outlets
end
# GET /contacts/1
def show
render json: #contact, include: :outlets
end
# POST /contacts
def create
#contact = Contact.new(contact_params)
if #contact.save
render json: #contact, status: :created, location: #contact
else
render json: #contact.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /contacts/1
def update
if #contact.outlets
#contact.outlets.delete_all
end
if params[:outlets]
contactOutlets = params[:outlets]
contactOutlets.each do |outlet|
#contact.outlets << Outlet.find(outlet[:key])
end
end
if #contact.update(contact_params)
render json: #contact, include: :outlets
else
render json: #contact.errors, status: :unprocessable_entity
end
end
# DELETE /contacts/1
def destroy
#contact.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_contact
#contact = Contact.find(params[:id])
end
# Only allow a list of trusted parameters through.
def contact_params
params.require(:contact).permit(:name, :email, :bio, :image_url, outlet_ids:[])
end
end

HABTM relationship with rails API does not work

I am new in Ruby on Rails. I am making a Rails API using Rails 5.1, active record serializer, doorkeeper and devise gem.
I have an Order table and it has many products. The relation between order and product is many-to-many.
Order model:
class Order < ApplicationRecord
validates_presence_of :brute, :net
has_and_belongs_to_many :products
end
Product model:
class Product < ApplicationRecord
belongs_to :category
validates_presence_of :name, :price
validates_uniqueness_of :name
has_and_belongs_to_many :orders
end
I have a join table named orders_products.
Order serializer:
class OrderSerializer < ActiveModel::Serializer
attributes :id, :discount, :brute, :net, :payed, :payed_at, :products
def products
object.products.map do |product|
ProductSerializer.new(product, scope: scope, root: false, event: object)
end
end
end
Product serializer:
class ProductSerializer < ActiveModel::Serializer
attributes :id, :name, :price, :description
has_one :category
end
Order controller:
module Api
class OrdersController < ApiController
before_action :set_order, only: [:show, :update, :destroy]
# GET /api/orders
def index
#orders = Order.all
render json: #orders
end
# GET /api/orders/1
def show
render json: #order
end
# POST /api/orders
def create
#order = Order.new(order_params)
if #order.save
render json: #order, status: :created, location: api_order_url(#order)
else
render json: #order.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /api/orders/1
def update
if #order.present?
if #order.update(order_params)
render json: #order
else
render json: #order.errors, status: :unprocessable_entity
end
end
end
# DELETE /api/orders/1
def destroy
#order.destroy if #order.present?
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
#order = Order.find(params[:id])
rescue ActiveRecord::RecordNotFound
Rails.logger.error{ 'Order record is not found' }
nil
end
# Only allow a trusted parameter "white list" through.
def order_params
params.require(:order).permit(:discount, :brute, :net, :payed, :payed_at, product_ids: [])
end
end
end
When I post some order json data from API generator app like Postman/Insomnia, Order is being saved in orders table but no data saved in orders_products join table.
My request(POST http://localhost:3000/api/orders) of order json:
{
"discount": 110,
"brute": 100,
"net": 200,
"payed": null,
"payed_at": null,
"product_ids": [3]
}
I try to find the solution but I failed.
Finally I have solved in your problem.Just add an attribute in your model.
Order Model:
class Order < ApplicationRecord
attribute :product_ids
validates_presence_of :brute, :net
has_and_belongs_to_many :products
end
Order Serializer:
class OrderSerializer < ActiveModel::Serializer
attributes :id, :discount, :brute, :net, :payed, :payed_at
has_many :products
end
And create method in your order api:
# POST /api/orders
def create
#order = Order.new(order_params)
if #order.save
# Find products
#products = Product.where(id: order_params[:product_ids])
# Create join table records
#products.each { |product| product.orders << #order }
render json: #order, status: :created, location: api_order_url(#order)
else
render json: #order.errors, status: :unprocessable_entity
end
end
I have tested in locally and it works! Happy Programming :)
As far as I know, Rails doesn't automatically handle creating the join records when given a list of ids. Therefore when you're calling #order = Order.new(order_params) and expecting it to know how to handle product_ids: [3], it's just ignoring it.
If you modify your create endpoint with the below, you should see the join records being created.
# POST /api/orders
def create
#order = Order.new(order_params)
if #order.save
# Find products
#products = Product.where(id: order_params[:product_ids])
# Create join table records
#products.each { |product| product.orders << order }
render json: #order, status: :created, location: api_order_url(#order)
else
render json: #order.errors, status: :unprocessable_entity
end
end
This is just one possible solution that doesn't do any error checking. Depending how secure and robust your application needs to be you may need to create a service that wraps this and handles validating that products are found before creating the order and associating the records.
EDIT: OrderSerializer
Once you've verified that the join table records are being created properly. Check that your serializers are working, they have great documentation. I believe you can swap out your current products method in the OrderSerializer with this:
class OrderSerializer < ActiveModel::Serializer
attributes :id, :discount, :brute, :net, :payed, :payed_at, :products
def products
object.products.map do |product|
ProductSerializer.new(product).serializable_hash
end
end
end

Rails - routes - weird errors

I am making a rails 4 app.
I just created a scaffold for Universities.
The universities table has three attributes, being :name, :logo, :post_code.
I created three universities as a test. They come up in the console.
The university.rb model has these associations:
The university model has these associations:
has_many :faculties
has_many :students
has_many :academics#, through: :researchers
has_many :educators
has_many :faculties
has_many :courses, through: :faculties
has_many :programs#, through: :academics
has_many :alumnus
has_one :policy_ip
has_one :policy_publication
has_one :policy_commerciality
has_many :eaip_assets
has_many :commercial_ip_assets
has_many :community_activities
has_many :ip_transfer_successes
has_many :spin_outs
has_many :ip_asset_managers#, through: :universities
has_many :expression_of_interest_options#, through: :ip_asset_manager, -> { where submitted: true }
has_many :expression_of_interest_assignments#, through: :ip_asset_manager, -> { where submitted: true }
has_many :expression_of_interest_licensings#, through: :ip_asset_manager, -> { where submitted: true }
has_many :expression_of_interest_collaborations#, through: :ip_asset_manager, -> { where submitted: true }
has_many :expression_of_interest_spin_outs#, through: :ip_asset_manager, -> { where submitted: true }
has_many :awards
has_many :profiles
The view university#show has:
<div class="col-md-7 col-md-offset-1">
<div class="profilet"><%= #university.name %></div>
<%= link_to 'Edit', edit_university_path(#university) %> |
<%= link_to 'Back', universities_path %>
The first error I get (on each of my 3 records) is:
undefined method `name' for nil:NilClass
When I change the line so that it is on:
<div class="profilet"><%= #university.try(:name) %></div>
I get an error on the 'edit' link that says:
No route matches {:action=>"edit", :controller=>"universities", :id=>nil} missing required keys: [:id]
When I delete the edit link and try again, I get a blank page with a 'back' link.
I can't understand whats going wrong. My console shows I definitely have 3 records in the university table (each with an id 1, 2 or 3). My routes are resources - (as they are with all of my other models) and this is the first problem I've encountered with the edit link.
I have strong params in my universities controller for each of the three attributes in the table, so I"m stuck for things to try to do to fix this.
Any ideas?
The universities controller has:
class UniversitiesController < ApplicationController
# before_action :set_university, only: [:show, :edit, :update, :destroy]
# GET /universities
# GET /universities.json
def index
#universities = University.all
end
# GET /universities/1
# GET /universities/1.json
def show
end
# GET /universities/new
def new
#university = University.new
end
# GET /universities/1/edit
def edit
end
# POST /universities
# POST /universities.json
def create
#university = University.new(university_params)
respond_to do |format|
if #university.save
format.html { redirect_to #university, notice: 'University was successfully created.' }
format.json { render action: 'show', status: :created, location: #university }
else
format.html { render action: 'new' }
format.json { render json: #university.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /universities/1
# PATCH/PUT /universities/1.json
def update
respond_to do |format|
if #university.update(university_params)
format.html { redirect_to #university, notice: 'University was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #university.errors, status: :unprocessable_entity }
end
end
end
# DELETE /universities/1
# DELETE /universities/1.json
def destroy
#university.destroy
respond_to do |format|
format.html { redirect_to universities_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_university
#university = University.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def university_params
params[:university].permit(:name, :logo, :post_code)
end
end
It means you didn't have object university in the actions. You have to enable the line below:
before_action :set_university, only: [:show, :edit, :update, :destroy]
The associated instance variable #university is nil therefore the route helper could not generate a route for it.
Please check your controller's edit action and fix the problem there.
You have #university with the id=nil, if you want to use edit url helper you need to provide #university entity with the id. In other words you can edit record that exists in DB, otherwise you should create new.
Wow you have a lot of problems here.
undefined method `name' for nil:NilClass
This means one of your variables is not initialized. The cause of this is where the fun begins.
When you define <%= #university.x %>, you're calling a method on your #university variable. If that variable is not populated with any data, or is undefined, Ruby automatically assigns the NilClass class to it.
You mention you're seeing this error when referencing the #university variable. This means either in your routes or controller, it's not being populated.
Here's how to fix it:
#config/routes.rb
resources :universities #-> url.com/universities/:id
#app/controllers/universities_controller.rb
class UniversitiesController < ApplicationController
before_action :set_university, only: [:show, :edit, :update, :destroy]
def index
#universities = University.all
end
def edit
end
def show
end
end
This should give you the capacity to use the following:
#app/views/universities/show.html.erb
<% if #university %>
<%= #university.name %>
<% end %>

Rails Has_Many :Through confusion

I'm working on creating a basic survey app as I'm learning rails. I've setup a has_many through relationship between the surveys as the questions (as questions may be used in multiple surveys). I've been struggling with adding a question to a survey though. Any idea what I need to do to create a new surveytization when creating my new question (and thus adding the question to the survey)? I'm able to do it in the console but am struggling with translating that to the controllers/views/params - if you know of any good documentation about those I'd love to check them out to (but thus far haven't found much).
It seems to error out when I try to assign my #survey variable using the :survey_id in the params I'm sending to the Question controller.
I really appreciate your help!
Question.rb:
class Question < ActiveRecord::Base
has_many :answers, dependent: :delete_all
validates :title, presence: true
has_many :surveytizations
has_many :surveys, :through => :surveytizations
end
Survey.rb
class Survey < ActiveRecord::Base
has_many :surveytizations
has_many :questions, :through => :surveytizations
end
Surveytization.rb:
class Surveytization < ActiveRecord::Base
has_many :surveys
has_many :questions
validates :survey_id, presence: true
validates :question_id, presence:true
end
SurveyController.rb:
class SurveysController < ApplicationController
before_action :set_survey, only: [:show, :edit, :update, :destroy]
before_action :set_question
# GET /surveys
# GET /surveys.json
def index
#surveys = Survey.all
end
# GET /surveys/1
# GET /surveys/1.json
def show
end
# GET /surveys/new
def new
#survey = Survey.new
end
# GET /surveys/1/edit
def edit
end
# POST /surveys
# POST /surveys.json
def create
#survey = Survey.new(survey_params)
respond_to do |format|
if #survey.save
format.html { redirect_to #survey, notice: 'Survey was successfully created.' }
format.json { render action: 'show', status: :created, location: #survey }
else
format.html { render action: 'new' }
format.json { render json: #survey.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /surveys/1
# PATCH/PUT /surveys/1.json
def update
respond_to do |format|
if #survey.update(survey_params)
format.html { redirect_to #survey, notice: 'Survey was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #survey.errors, status: :unprocessable_entity }
end
end
end
# DELETE /surveys/1
# DELETE /surveys/1.json
def destroy
#survey.destroy
respond_to do |format|
format.html { redirect_to surveys_url }
format.json { head :no_content }
end
end
def add_question(question)
surveytizations.create!(question_id: question.id)
end
def remove_question(question)
surveytizations.find_by(question_id: question.id).destroy
end
def find_question(question)
#question = surveytizations.find_by(question_id: question.id)
end
private
# Use callbacks to share common setup or constraints between actions.
def set_survey
#survey = Survey.find(params[:id])
end
def set_question
#question = Question.new
end
# Never trust parameters from the scary internet, only allow the white list through.
def survey_params
params.require(:survey).permit(:title)
end
end
Survey show.html.erb:
<p id="notice"><%= notice %></p>
<p>
<strong>Title:</strong>
<%= #survey.title %>
</p>
<%= link_to 'Edit', edit_survey_path(#survey) %> |
<%= link_to 'Back', surveys_path %>
<%= link_to "Add Question", new_question_path(:survey_id => #survey.id)%>
QuestionController:
class QuestionsController < ApplicationController
before_action :set_question, only: [:show, :edit, :update, :destroy]
# GET /questions
# GET /questions.json
def index
#questions = Question.all
end
# GET /questions/1
# GET /questions/1.json
def show
#answers = #question.answers
end
# GET /questions/new
def new
#question = Question.new
#survey = Survey.find(:survey_id)
end
# GET /questions/1/edit
def edit
end
# POST /questions
# POST /questions.json
def create
#question = Question.new(question_params)
respond_to do |format|
if #question.save
format.html { redirect_to #question, notice: 'Question was successfully created.' }
format.json { render action: 'show', status: :created, location: #question }
else
format.html { render action: 'new' }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /questions/1
# PATCH/PUT /questions/1.json
def update
respond_to do |format|
if #question.update(question_params)
format.html { redirect_to #question, notice: 'Question was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
# DELETE /questions/1
# DELETE /questions/1.json
def destroy
#question.destroy
respond_to do |format|
format.html { redirect_to questions_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_question
#question = Question.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def question_params
params.require(:question).permit(:title, :single_response, :surveytization)
end
end
One problem is your join relation should have belongs_to instead of has_many, to get the has_many through working:
class Surveytization < ActiveRecord::Base
belongs_to :survey
belongs_to :question
validates :survey_id, presence: true
validates :question_id, presence:true
end
Notice the :survey and :question are singular name in the belongs_to
To Add a question to a survey you can
# create new question or find existing question and store it in #question
#question
# get the survey into #survey
#survey
#survey.questions << #question
This will magically create the surveytization as well. Now that question will belong to that survey.
You Don't even have to call #survey.save! after.

How do I associate data with each other using a join table?

I have three models: Lesson, Situation, Fate(join table).
In this app, A situation can have many lessons and a lesson can belong to multiple situations.
I would essentially like the tables to look like this.
Situation
id.....name.....................description
1.....Ordering Food......You go into a restaurant and order food.
2.....Introduce yourself.You meet someone for the first time and you introduce yourself.
Lesson
id.....name............description..............lesson_text
1......Order food....How to order food..Blah blah blah, this is how you order food.
2......Call the waiter.How to call the waiter Blah blah blah, this is how you call the waiter
3 Pay for food How to pay for food Blah blah blah, this is how you pay for food.
4 Greet a person How to greet a person Blah blah blah, this is how you greet a person.
5 Ask a question How to ask a question Blah blah blah, this is how you ask a question.
Fate
situation_id lesson_id required
1.................1...............yes
1.................2...............yes
1.................3...............no
2.................3...............yes
2.................4...............yes
2.................5...............yes
I have the tables set up but I'm not sure how I would associate a lesson to a situation.
This is what my application looks like currently
Situations controller
class SituationsController < ApplicationController
def index
#situations = Situation.all
end
def new
#situation = Situation.new
end
def create
#situation = Situation.new(params[:situation])
respond_to do |format|
if #situation.save
format.html { redirect_to #situation }
end
end
end
def show
#situation = Situation.find(params[:id])
#lesson = #situation.lessons.new
end
def edit
#situation = Situation.find(params[:id])
end
def update
#situation = Situation.find(params[:id])
respond_to do |format|
if #situation.update_attributes(params[:situation])
format.html { redirect_to #situation }
end
end
end
def destroy
#situation = Situation.find(params[:id])
#situation.destroy
respond_to do |format|
format.html { redirect_to situations_path }
end
end
end
Lessons controller
class LessonsController < ApplicationController
def index
#lessons = Lesson.all
end
def new
#lesson = Lesson.new
end
def create
#lesson = Lesson.new(params[:lesson])
respond_to do |format|
if #lesson.save
format.html { redirect_to #lesson }
end
end
end
def show
#lesson = Lesson.find(params[:id])
end
def edit
#lesson = Lesson.find(params[:id])
end
def update
#lesson = Lesson.find(params[:id])
respond_to do |format|
if #lesson.update_attributes(params[:lesson])
format.html { redirect_to #lesson }
end
end
end
def destroy
#lesson = Lesson.find(params[:id])
#lesson.destroy
respond_to do |format|
format.html { redirect_to lessons_path }
end
end
end
Routes
root :to => 'situations#index'
resources :situations do
resources :lessons
end
resources :difficulties
Situation.rb
class Situation < ActiveRecord::Base
attr_accessible :name, :description
has_many :fates
has_many :lessons, :through => :fates
end
Lesson.rb
class Lesson < ActiveRecord::Base
attr_accessible :name, :description, :difficulty_id, :lesson_text
has_many :fates
has_many :situations, :through => :fates
end
Fate.rb
class Fate < ActiveRecord::Base
belongs_to :lesson
belongs_to :situation
end
Thanks for the help! and I'm really sorry about the messy formatting.
So if you are creating a new situation and want to also create new lessons that will be associated with it..
app/models/situation.rb
attr_accessible :name, :description, :difficulty_id, :lesson_text, :lessons_attributes
accepts_nested_attributes_for :lessons
app/controllers/situations_controller.rb
def new
#situation = Situation.new
2.times do{#situation.lessons.build}
respond_to do |format|
format.html
end
end
app/views/lessons/_form.html.erb
<% form_for #situation do |f| %>
<%= f.text_field :name %>
<%= f.text_field :description %>
<% f.fields_for :situations do |lesson_field| %>
<%= lesson_field.text_field :name %>
<%= lesson_field.text_field :lesson_text %>
<% end %>
<%= f.submit %>
<% end %>
Essentially you need a nested form (there is plenty examples). I typed this off the iPhone, hope it works )

Resources