【问题标题】:Fields for a record in a 'has many' association inside a form表单内“有很多”关联中的记录字段
【发布时间】:2011-01-29 06:00:48
【问题描述】:

我有一个Topic,其中有很多Posts。创建主题时,它会随之创建第一个帖子。

我在表单中包含了帖子字段:

= form_for @topic do |topic_form|

  # ...

  = topic_form.fields_for @post do |post_fields|
    = post_fields.label :content
    %br/
    = post_fields.text_area :content
    %br/

这是我的TopicsController 的样子:

def new
  @topic = Topic.new
  @post = Post.new
  respond_with @topic
end

def create
  @topic = Topic.create params[:topic]
  @post = @topic.create_post params[:topic][:post]
  respond_with @topic, location: topic_url(@topic)
end

我在create 方法的第一行得到一个UnknownAttributeError - unknown attribute: post。我猜这是因为帖子哈希包含在请求的主题哈希中:

"topic" => { "title" => "...", "post" => { "content" => "..." } }

我该如何解决这种情况?

【问题讨论】:

    标签: ruby-on-rails forms associations has-many


    【解决方案1】:
    1. 您的Topic 模型中应该有一个accepts_nested_attributes_for :posts
    2. 您的表单应该有= topic_form.fields_for :posts do |post_fields| 而不是@post
    3. 您的newcreate 方法都不需要@post = .... 行。当您保存 @topic 时,它会自动为您保存新的关联帖子。

    下面是对表单中嵌套属性的一个很好的解释:http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

    【讨论】:

    • 我按照指示做了,但我仍然收到完全相同的错误。
    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多