Two simple model:
Record
class Record < ActiveRecord::Base
has_many :comments
validates :title, presence: true,
length: { minimum: 5 }
end
Comment
class Comment < ActiveRecord::Base
belongs_to :record
end
in viewer
<h2>Add a comment: </h2>
<%= form_for([@record, @record.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br>
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
in controller
def create
@record = Record.find(params[:record_id])
@comment = @record.comments.create(comment_params)
logger.debug "comment check: #{@comment.attributes.inspect}"
redirect_to record_path(@record)
end
Logger information:
I, [2014-06-26T14:13:49.802139 #20539] INFO -- : Processing by CommentsController#create as HTML
I, [2014-06-26T14:13:49.802236 #20539] INFO -- : Processing by CommentsController#create as HTML
I, [2014-06-26T14:13:49.802300 #20539] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"12u1/KgN8baCy8Jn/TJi3Ux7m258FZPfraHGUhl9WnM=", "comment"=>{"commenter"=>"qwe", "body"=>"asdsa"}, "commit"=>"Create Comment", "record_id"=>"4"}
I, [2014-06-26T14:13:49.802338 #20539] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"12u1/KgN8baCy8Jn/TJi3Ux7m258FZPfraHGUhl9WnM=", "comment"=>{"commenter"=>"qwe", "body"=>"asdsa"}, "commit"=>"Create Comment", "record_id"=>"4"}
D, [2014-06-26T14:13:49.807062 #20539] DEBUG -- : Record Load (0.1ms) SELECT "records".* FROM "records" WHERE "records"."id" = ? LIMIT 1 [["id", 4]]
D, [2014-06-26T14:13:49.807138 #20539] DEBUG -- : Record Load (0.1ms) SELECT "records".* FROM "records" WHERE "records"."id" = ? LIMIT 1 [["id", 4]]
D, [2014-06-26T14:13:49.810514 #20539] DEBUG -- : (0.1ms) begin transaction
D, [2014-06-26T14:13:49.810599 #20539] DEBUG -- : (0.1ms) begin transaction
D, [2014-06-26T14:13:49.821927 #20539] DEBUG -- : (0.1ms) commit transaction
D, [2014-06-26T14:13:49.822023 #20539] DEBUG -- : (0.1ms) commit transaction
D, [2014-06-26T14:13:49.822159 #20539] DEBUG -- : comment check: {"id"=>nil, "commenter"=>"qwe", "body"=>"asdsa", "record_id"=>nil, "created_at"=>nil, "updated_at"=>nil}
D, [2014-06-26T14:13:49.822201 #20539] DEBUG -- : comment check: {"id"=>nil, "commenter"=>"qwe", "body"=>"asdsa", "record_id"=>nil, "created_at"=>nil, "updated_at"=>nil}
I, [2014-06-26T14:13:49.822667 #20539] INFO -- : Redirected to http://0.0.0.0:3000/records/4
I, [2014-06-26T14:13:49.822714 #20539] INFO -- : Redirected to http://0.0.0.0:3000/records/4
When I create comment, data doesn't write to database any suggestion? By the way, why each logger information has double output?
Comment.create) it actually creates a newRecordinstead. I had to remove thebelongs_to :recordassociation to prevent that from happening and I have no idea why it isn't working right now. Very very odd.