Neil wrote:script/generate migration add_user_id_to_comments# ... and in your migration
class AddUserIdToComments < ActiveRecord::Migration
def self.up
add_column :comments, :user_id, :integer
end
def self.down
remove_column :comments, :user_id
end
end
Hi, I'm currently struggling with (I guess) a foreign key issue that relates directly to your, (presumably hypothetical) migration script...
I am attempting to enable display of the (logged on) Users name along with the comment.
I have a comments table with both story_id:int AND user_id:int columns.
I added user has_many :comments, story has_many :comments, and comment belongs_to :story [and] :user in the respective [model].rb's.
Comment form and display both happen on the story page:
<%=h @story.name %></span></a><br /> <span class="caption">
<%= render :partial => 'comment', :collection => @story.comments %>
</span><br />
<% form_for @comment do|f| %>
<%= f.error_messages %>
<%= f.hidden_field :story_id %>
<%= f.hidden_field :user_id %>
<p>
<%= f.label :"Add a Comment" %><br />
<%= f.text_area :comment %>
</p>
<p>
<%= f.submit "Submit" %>
</p>
<% end %>
And here is my comments_controller.rb:
class CommentsController < ApplicationController
before_filter :login_required, :only => [ :create, :destroy ]
def create
@comment = Comment.new(params[:comment])
if @comment.save
flash[:notice] = 'Comment was successfully created.'
redirect_to(@comment.story)
else
flash[:notice] = "Error creating comment: #{@comment.errors}"
redirect_to(@comment.story)
end
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
redirect_to(@comment.story)
end
end
When I post a comment and review the output in the console, I can see the user_id is being flagged correctly in mysql, but it isn't being passed along by CommentsController#create to be saved to the record (saved as "null").
The story_id is being flagged and saved. along with the body of the comment and timestamp:
---- console output ---
Processing CommentsController#create (for 127.0.0.1 at 2009-07-09 16:57:15) [POST]
Parameters: {"comment"=>{"comment"=>"...", "story_id"=>"3", "user_id"=>""}, "commit"=>"Submit", "authenticity_token"=>"..."}
[0mSELECT * FROM `users` WHERE (`users`.`id` = 1) LIMIT 1
[0;1mINSERT INTO `comments` (`comment`, `created_at`, `updated_at`, `story_id`, `user_id`) VALUES('...', '2009-07-09 20:57:15', '2009-07-09 20:57:15', 3, NULL)
----------------------
So, in a nutshell, the new comment record is picking up the story_id, but not the user_id.
Any ideas on how this can be fixed? Is it a foreign key issue?
I feel like I'm just a line or two of code away from getting this to work...
Thanks!