I would like to create pages for Discussions on a website, and on those discussion pages have users be able to write posts. The posts need to belong to the discussion and a user, and the discussion to a user.
I have thus created two models, two controllers, and one partial to put on the discussion show page. Note that the redirects from the controllers are just assigned to root_pages and others in no logical fashion, as I wanted to deal with redirects once I got the form working. I didn’t attach the user model, as it is long and I didn’t think it was necessary.
My problem is that I can’t get the post controller to assign the correct discussion id to a new post. I’d like for this to be recorded, so that posts are associated to the author user_id (which works) and the discussion_id. I know that using @post.discussion_id = @discussion.id won’t assign this properly, but I have tested @post.discussion_id = 1 to see if the rest of the code works (it does).
How do I change the set-up of the forms/controllers to assign the discussion_id here? Any help would be much appreciated!
Discussion Controller:
class DiscussionsController < ApplicationController
def show
@discussion = Discussion.find(params[:id])
@title = @discussion.title
@post = Post.new if signed_in?
end
end
Discussion Model:
class Discussion < ActiveRecord::Base
attr_accessible :title, :prompt
belongs_to :user
validates :title, :presence => true, :length => { :within => 5..100 }
validates :prompt, :presence => true, :length => { :within => 5..250 }
validates :user_id, :presence => true
has_many :posts, :dependent => :destroy
default_scope :order => 'discussions.created_at DESC'
end
Post Controller:
class PostsController < ApplicationController
def create
@post = current_user.posts.build(params[:post])
@post.discussion_id = @discussion.id
if @post.save
redirect_to discussion_path
else
redirect_to user_path
end
end
end
Post Model:
class Post < ActiveRecord::Base
attr_accessible :content
validates :content, :presence => true, :length => { :maximum => 10000 }
validates :user_id, :presence => true
validates :discussion_id, :presence => true
belongs_to :user
belongs_to :discussion
default_scope :order => 'posts.created_at ASC'
end
Partial for post form:
<%= form_for @post do |f| %>
<%= render 'shared/error_messages' %>
<div class="field">
<%= f.text_area :content, :class => "inputform largeinputform round" %>
</div>
<div class="actions">
<%= f.submit "Post", :class => "submitbutton round" %>
</div>
<% end %>
Your issue is that you do not have a mechanism to get the @discussion into the post controller One approach might be to put the discussion id in a hidden field in your partial form and then read it in your controller as a param.
Lance