【问题标题】:Can't create form_for associated models无法为关联模型创建 form_for
【发布时间】:2013-12-11 07:31:29
【问题描述】:

我正在编写一个简单的 Web 应用程序,我喜欢将其称为 PMS(项目管理系统)。对于这个应用程序,我有 2 个模型 ProjectsStudents。我已经在这两个模型之间建立了(我猜......因为我是新手)关联。项目有很多学生,但学生属于一个项目(可能会随着时间而改变)。

但我的问题是如何让所有的东西一起工作。我不知道如何在新项目表单中插入新学生。我什么都试过了,还是不行!

这是我的源文件:

项目控制器:

class ProjectsController < ApplicationController
  def show
    @projects = Project.all
  end

  def create
    @project = Project.new(project_params)
    @project.status = "Waiting"
    @project.save
    redirect_to root_path
  end

  private
    def project_params
      params.require(:project).permit(:title, :lecturer)
    end
end

学生管理员:

class StudentsController < ApplicationController
  def create
    @project = Project.find(params[:project_id])
    @student = @project.students.create(params[:student])
    @student.save
  end
end

型号:

class Project < ActiveRecord::Base
  has_many :students
end

class Student < ActiveRecord::Base
  belongs_to :project
end

查看:

添加新项目

<%= form_for :project, url: projects_path do |f| %>
    <p>
        <%= f.label :title %>
        <%= f.text_field :title %>
    </p>
    <p>
        <%= f.label :lecturer %>
        <%= f.text_field :lecturer %>
    </p>
        <%= form_for([@project, @project.students.build]) do |s| %>
          <p>
            <%= s.label :name %><br />
            <%= s.text_field :name %>
          </p>
        <% end %>
    <p>
        <%= f.submit %>
    </p>
<% end %>

路线:

RoRPMS::Application.routes.draw do
  # You can have the root of your site routed with "root"
  root 'projects#show'

  resources :projects do
    resources :students
  end
end

【问题讨论】:

  • 使用save时,必须检查布尔结果。可以尝试用save!代替save,如果无法保存对象会抛出异常,提示错误。
  • 好吧,我明白了,但这仍然不是我要处理的问题......

标签: ruby-on-rails associations form-for nested-form-for


【解决方案1】:

您也可以使用“nested_form”与学生一起创建项目

<%= nested_form_for @project do |f| %>
    <p>
        <%= f.label :title %>
        <%= f.text_field :title %>
    </p>
    <p>
        <%= f.label :lecturer %>
        <%= f.text_field :lecturer %>
    </p>
        <%= fields_for :students do |s| %>
          <p>
            <%= s.label :name %><br />
            <%= s.text_field :name %>
          </p>
        <% end %>
        <%= f.link_to_add "Add new student", :students %>
    <p>
        <%= f.submit %>
    </p>
<% end %>

在项目模型中添加

accepts_nested_attributes_for :students

【讨论】:

  • 您是否在 gem 文件中添加了“nested_form”gem 如果是,那么您遇到了什么错误?
猜你喜欢
  • 2017-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 2022-08-18
相关资源
最近更新 更多