ينتمي إلى الكائنات في القضبان
-
30-09-2019 - |
سؤال
مرحبًا ، أقوم حاليًا ببناء تطبيق منتدى صغير مع Rails (3). أنا جديد إلى حد ما في مسألة القضبان وحصلت على المواضيع.
لدي نموذجان (Topic & Topic_Reply)
نموذج الموضوع:
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
نموذج رد الموضوع:
class TopicReply < ActiveRecord::Base
belongs_to :topic
belongs_to :user
end
عندما أقوم بإنشاء موضوع يتم عرض كل شيء على ما يرام باستثناء topic_replies (جميع المنشورات في الموضوع)
السبب هو: كائن topic_reply يحفظ كل شيء بشكل صحيح باستثناء أنه لا يحفظ topic_id في الكائن وبالتالي في ديسيبل الخاص بي.
إليك جزء من وحدة تحكم الموضوع الخاصة بي لإنشاء موضوع:
# 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
هل لدى أي شخص فكرة عما أفعله بشكل خاطئ إذا نشرت معلومات أقل ، فأخبرني بأنني سأضيف ما تحتاجه.
شكرا مقدما
المحلول
يجب تسمية مفاتيحك الأجنبية topic_id
, poster_id
و board_id
لأن هذه هي القيم الافتراضية في القضبان. أنت لا تحدد الأعمدة غير الافتراضية في النماذج الخاصة بك ، لذلك لا يمكن أن يعمل الكود الحالي.