If you want to create a new syllabus
in your show
action of a specific course
, you can add this to your controllers and views:
courses_controller.rb
@course = Course.find(params[:id])
# Build a new @syllabus object, only if there is none for the current course
unless @course.syllabus
@syllabus = @course.build_syllabus
end
views/courses/show.html.erb
# Show the syllabus name if there is one, or show the form to create a new one
<% if @course.syllabus.name %>
<p>Syllabus: <%= @course.syllabus.name %>p>
<% else %>
<p>Create Syllabus:p>
<%= form_for([@course, @syllabus]) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
div>
<div class="actions">
<%= f.submit %>
div>
<% end %>
<% end %>
syllabuses_controller.rb
def create
@course = Course.find(params[:course_id])
# Build new syllabus object based on form input
@syllabus = @course.build_syllabus(params[:syllabus])
if @syllabus.save
# redirect to /course/:id
redirect_to @course, notice: 'Syllabus was successfully created.' }
end
end
course.rb
class Course < ActiveRecord::Base
attr_accessible :name
has_one :syllabus
end
syllabus.rb
class Syllabus < ActiveRecord::Base
belongs_to :course
attr_accessible :name, :course_id
end
Some things that I left out but you should still include:
manpreet
Best Answer
2 years ago
I have an app where users can create courses, and each course has_one syllabus. How could I go about configuring my courses and syllabuses (I know it's Syllabi but apparently Rails doesn't) controller, and my routes, so on a course's page there is a link to create or show the course's syllabus, and a link back to the course from the show syllabus page?
In my routes I have:
Currently , so the course_id will be saved in the syllabus table in my courses_controller, I have:
then in my courses show page I have:
then in my create_syllabus form (in my courses views folder) I have tried starting it off with:
and I get an undefined method error for each of those.