Alright. First off, I am new to Rails and this is the first project I am trying to build from scratch.
I have 2 models: Course and Question. I want to be able to add Questions to a specific Course, so Course is the parent model of Question. (Course has_many :questions and Question belongs_to :course)
From courses/show I render a partial:
<%= render 'questions/form', :question => @course.questions.build %>
and the partial questions/_form:
<%= form_for(question) do |f| %>
<div class="field">
<%= f.text_field :content %>
<%= f.hidden_field :course_id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and here is the create function:
def create
@course = Course.find(params[:question][:course_id])
question = @course.questions.build
if question.save
redirect_to @course
end
end
But in my console I get the following output:
Started POST "/questions" for 127.0.0.1 at 2011-10-27 19:06:25 -0400
Processing by QuestionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"negkm0uXBez8sisXl3pFVgfvhcDkixFPiMjzM68mNVU=", "question"=>{"content"=>"hallo", "course_id"=>"2"}, "commit"=>"Create Question"}
Course Load (0.3ms) SELECT "courses".* FROM "courses" WHERE "courses"."id" = $1 LIMIT 1 [["id", "2"]]
(0.3ms) BEGIN
SQL (0.5ms) INSERT INTO "questions" ("content", "course_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["content", nil], ["course_id", 2], ["created_at", Thu, 27 Oct 2011 23:06:25 UTC +00:00], ["updated_at", Thu, 27 Oct 2011 23:06:25 UTC +00:00]]
(1.6ms) COMMIT
What I don’t understand is that the Parameters include “content”=>”hallo”, but the value inserted into my table is nil…
I am fairly sure that I made a jumbled up mess because this is the product of an hour or trial and error, if anyone has a small change I should make or even a completely different way to achieve the same goal, that would be much appreciated.
You are looking up a
coursewith acourse_id, if one exists, but you make no further references to theparamshash-like object, nor thecontentparameter withinparams— so it can never be saved. Try: