嗨,我目前正在使用Rails(3)构建一个小论坛申请。我在铁轨方面很新,我陷入了主题。

我有2个型号(主题和主题_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

当我创建主题时

原因是:我的主题_reply对象正确保存了所有内容,除非它不能将主题_id保存在对象中,从而将其保存在我的db中。

这是我的主题控制器创建一个主题的一部分:

 # 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_idboard_id 由于这些是导轨中的默认值。您没有在模型中定义非默认列,因此当前代码无法正常工作。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top