Rails表单 - 提交到子类

时间:2013-05-15 00:08:00

标签: ruby-on-rails ruby

铁道新手,如果答案显而易见,请道歉。 如果我有2个模型,一个用户和注释,一个(1:N)关系。 当我创建用户时,我也在创建评论。

我遇到的问题是如何编写表单,或者用户类中是否与注释将与用户关联?

  <%= form_for(@user) do |f| %>
    <%= f.text_field :name %>
    <%= f.text_area :comment ???? %>
    <%= f.submit %>
  <% end %>  

2 个答案:

答案 0 :(得分:1)

我想你有一个评论模型......

在user.rb中添加此内容

has_many :comments
accepts_nested_attributes_for :comments

在你的控制器里?

def new
  @user = User.new
  @user.comments.build
end

在表单视图中:

<%= form_for @user do |f| %>
  <%= f.text_field :name %>
  <%= f.fields_for :comments do |comment_form| %>
    <%= comment_form.text_field :description %>
  <% end %>
<% end %>

答案 1 :(得分:0)

假设您的用户表单正确无误,您只需在用户模型中添加注释作为属性即可。你不需要单独的评论模型。

# schema

create_table "posts", :force => true do |t|
t.string   "name"
t.text     "comment"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false

您可以创建迁移以将评论属性添加到用户模型

rails g migration add_comment_to_user comment:text

如果您需要,可以删除评论模型

然后你可以使用你拥有的表格

<%= form_for(@user) do |f| %>
  <%= f.text_field :name %>
  <%= f.text_area :comment %>
  <%= f.submit %>
<% end %>

您可能还想在表单中添加一些标签

<%= form_for(@user) do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  <%= f.label :comment %>
  <%= f.text_area :comment %>
  <%= f.submit %>
<% end %>

希望这能让你走上正轨