Topic: Newb Question Regarding Creating Records with Mulitple Foreign Keys

Hi All,

Been playing with RoR for a couple of hours now and i love it ! but ive hit a problem, im trying to create a forum type app and cant work out how to create my "comment" records, basically a comment has 2 foreign keys post_id and member_id, relevant code :

form:

<%= start_form_tag :action => 'comment', :id => @post%>
    <%= text_field 'comment', 'body'  %>
    <%= submit_tag 'Comment' %>
<%= end_form_tag %>

controller :

  def comment
    Post.find(params[:id]).comments.create(params[:comment])
    flash[:notice] = 'Comment Added.'
    redirect_to :action => "view", :id=>params[:id]
  end

models :

class Post< ActiveRecord::Base
  has_many :comments
  belongs_to :member
end

class Member < ActiveRecord::Base
  has_many :posts
  has_many :comments
  has_many :tags
end

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :member
end


So this works fine and the comment gets saved with the post_id populated, but how do i save the member_id ? (the member object is in the session)

Many thanks in advance for any help :)

Last edited by webbo (2006-12-10 12:04:56)

Re: Newb Question Regarding Creating Records with Mulitple Foreign Keys

You can add the member id to the params[:comment] hash like this:

Post.find(params[:id]).comments.create(params[:comment].merge(:member_id => session[:member_id]))

That line is getting kind of long, so you may want to split it up and add validation:

@post = Post.find(params[:id])
@comment = @post.comments.build(params[:comment])
@comment.member_id = session[:member_id]
if @comment.save
  #...
else
  #...
end

Railscasts - Free Ruby on Rails Screencasts

Re: Newb Question Regarding Creating Records with Mulitple Foreign Keys

Spot on !

Many thanks ryanb