Reputation:
Hi I'm currently building a little forum application with rails (3). I'm fairly new in the Rails matter and I got stuck with the topics.
I have 2 models (topic & topic_reply)
topic model:
class Topic < ActiveRecord::Base
belongs_to :board
belongs_to :user
has_many :topic_replies, :dependent => :destroy
TOPIC_TYPES = ["Non-support", "Question"]
validates :topic_type, :inclusion => TOPIC_TYPES
end
topic reply model:
class TopicReply < ActiveRecord::Base
belongs_to :topic
belongs_to :user
end
When I'm creating a topic everything is displaying fine except for the topic_replies (all the posts within the topic)
The reason is: my topic_reply object saves everything correctly except it doesn't save the the topic_id in the object and thus in my db.
here's a part of my topic controller to create a topic:
# GET /topics/new
# GET /topics/new.xml
def new
@topic = Topic.new
@topic_reply = @topic.topic_replies.build
respond_to do |format|
format.html # new.html.erb
end
end
# POST /topics
# POST /topics.xml
def create
@topic = Topic.new(params[:topic])
@topic.id_board = @board.id
@topic_reply = @topic.topic_replies.build(params[:topic_reply])
@topic_reply.id_topic = @topic.id
@topic_reply.id_poster = User.first.id
respond_to do |format|
if @topic.save && @topic_reply.save
format.html { redirect_to(topic_path("#{@board.name.parameterize}-#{@board.id}", "#{@topic.title.parameterize}-#{@topic.id}")) }
else
format.html { render :action => "new" }
end
end
end
does anyone have an idea what I'm doing wrong if I posted too less information let me know I'll add what you need.
Thanks in advance
Upvotes: 1
Views: 639
Reputation: 5398
Your foreign keys should be named topic_id
, poster_id
and board_id
as these are default values in Rails. You're not defining non-default columns in your models, so the current code can't work.
Upvotes: 2