我在ruby中遇到嵌套属性的问题

时间:2013-11-26 00:30:15

标签: ruby-on-rails rails-activerecord

我正在尝试在我的网站上创建一个类似论坛的论坛,​​但我遇到了嵌套属性的问题。我有一个拥有标题的Topic模型,我有一个包含内容的Post模型。我的主题模型中的代码包含

class Topic < ActiveRecord::Base

  belongs_to :forum
  belongs_to :user
  has_many :posts, :dependent => :destroy

  accepts_nested_attributes_for :posts

end

在我看来我试图像这样访问内容变量

<% if @topic.errors.any? %>
<div class="alert alert-danger"> 
<p>The form contains <%= pluralize(@topic.errors.count, "error") %>.</p>
</div>
<ul>
  <% @topic.errors.full_messages.each do |message| %>
  <li class="text-danger"> <%= message %> </li>
  <% end %>
</ul>
<% end %>

<div class='form-group'>
  <%= f.label :title, "Title*" %>
  <%= f.text_field :title, class: 'form-control' %>
</div>

<%= f.fields_for :posts do |ff| %>
 <div class='form-group'>
    <%= ff.label :content, "Content*" %>
    <%= ff.text_area :content, size: "25x6", class: 'form-control' %>
 </div>
<% end %>

这只是一个局部的,它在我的new.html.erb中运行但是当我运行它时它只显示我的标题文本字段而不是内容文本区域?任何人都有任何想法,如果他们有任何疑问,因为我没有解释得很好,请随时提出。

编辑:

这是我的主题控制器。

class TopicsController < ApplicationController

 def index
 end

 def new
  forum = Forum.find(params[:forum_id])
  @topic = forum.topics.build
  post = @topic.posts.build
 end

def create
  forum = Forum.find(params[:forum_id])
  @topic = forum.topics.build(topic_params)
  post = @topic.posts.build
  if @topic.save and post.save then
    flash[:success] = "Topic Posted"
    redirect_to @topic
  else
    render 'new'
  end
end

def show
end

def edit
end

def update
end

def destroy
  forum = Forum.find(params[:forum_id])
  @topic = Topic.find(params[:id])
  if current_user.admin? then
    @topic.destroy
    flash[:success] = @topic.title + " destroyed!"
    redirect_to forum_topic_path(forum)
  else
    redirect_to root_path
  end
end

private

def topic_params
  params.require(:topic).permit(:title, :content)
end

end

1 个答案:

答案 0 :(得分:0)

可能无法解决您的问题,但您需要修复一些语法:

def create
 topic = Topic.new(topic_params)
  if topic.save then
    flash[:success] = "Topic Posted"
    redirect_to @topic
  else
    render 'new'
  end
end

def topic_params
    params.require(:topic).permit(:title, post_attributes: [:content]).merge(:forum_id => params[:forum_id])
end

您的topics表格应该包含foreign_keys user_id&amp; forum_id title posts。您的topic_id表应具有外键{{1}}

这个 应该看你的代码。如果没有,那么查看呼叫的控制台错误会很有帮助

相关问题