为具有关联的对象创建表单

Creating form for an object which has an association

我有两个模型:project 和 todo。项目有很多待办事项。

所以我想创建一个表单,在其中 select 从组合框中选择项目类别,然后向其中添加待办事项。

例如: 我有以下几类:家庭、工作、学习。

在组合框的表单中,我 select 'study',然后在文本字段中,我拼写了 'make homework for monday' 之类的待办事项,然后按提交按钮。

project.rb

class Project < ActiveRecord::Base
  has_many :todos
end

todo.rb

class Todo < ActiveRecord::Base

  belongs_to :project

end

我的数据模式:

  create_table "projects", force: :cascade do |t|
    t.string   "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "todos", force: :cascade do |t|
    t.string   "text"
    t.boolean  "isCompleted"
    t.integer  "project_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

_form.html.erb

<%= form_for @project do |f| %>

  <div class="form_control">
    <%= f.select :title, options_for_select([["Work", "w"],
                                            ["Family", "f"],
                                           ["Study", "f"],
                                           ["TheRest", "t"]]) %>
  </div>

  <div class="form_control">
    *** HERE I NEED TO FIGURE OUT HOW TO ADD SOME DATA TO todo.text ***
  </div>  

  <div class="form_control">
    <%= f.submit 'Add' %>
  </div>
<% end %>

这是我显示所有项目及其待办事项的方式:

<% @projects.each do |project| %>
    <h2> <%= project.title %> </h2>
    <% project.todos.all.each do |todo| %>
      <p><%= todo.text %> <%= check_box('tag', todo.__id__, {checked: todo.isCompleted}) %></p>
    <% end %>
<% end %>

GitHub link : https://github.com/NanoBreaker/taskmanager

在您的待办事项表单中,您可以有一个 select 框来选择待办事项所属的项目:

# todos/_todo_form.html.erb
  <%= select_tag "project_id", options_for_select(Project.pluck(:title, :id)) %>

并且在您的 todos_controller create 操作中:

def create
  @project = Project.find(params[:project_id])
  @todo = @project.todos.new(todo_params)
  if @todo.save
    # success
  else 
    # error 
  end
end 

最后,允许 todo_params 中的 project_id:

def todo_params
  params.require(:todo).permit(:text, :project_id) # add any other attributes you want
end