行未添加到表,但未给出错误

时间:2019-12-01 02:09:08

标签: ruby-on-rails

我是Rails的新手。我有一个名为TeamMemberships的表,该表具有2个外键:一个到Users,另一个到Teams。我想从TeamMembership的{​​{1}}页向TeamMemberships表的show.html.erb表中添加一个Teams元素,以使Team外键是Team称为操作和User的内容将由表格确定。当我尝试添加TeamMembership时,页面将按预期方式重定向,但是,未添加表元素,也未给出错误消息。是什么原因造成的? 这是我的路线:

Rails.application.routes.draw do
  resources :instructors
  get 'static_pages/home'
  get 'static_pages/adminLanding'

  resources :audiences
  resources :comments
  resources :scores
  resources :projects
  resources :team_memberships
  resources :team_types
  resources :teams
  resources :users
  Rails.application.routes.draw do
    resources :teams do
      resources :team_memberships
    end
  end
  root 'static_pages#home'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

这是teams/show.html.erb页面上的链接:

<%= link_to 'Add a student', new_team_team_membership_path(@team.id) %>

这是new控制器中的TeamMemberships方法:

  def new
    @team_membership = TeamMembership.new(team_id: params[:team_id])
    @users = User.all

  end

以下是team_memberships/new.html.erb文件的格式:

<h1>New Team Membership</h1>

<%= form_for @team_membership do |f| %>
  <%= f.select :user_id, options_for_select(@users.collect{ |student| [student.first_name + ' ' +student.last_name, student.id]}) %>
    <%= f.submit %>
  <% end %>

<%= link_to 'Back', team_memberships_path %>

这是create控制器的TeamMemberships方法:

  def create
    @users = User.all
    @team_membership = TeamMembership.new(team_membership_params)

    respond_to do |format|
      if @team_membership.save
        format.html { redirect_to @team_membership, notice: 'Team membership was successfully created.' }
        format.json { render :show, status: :created, location: @team_membership }
      else
        format.html { render :new }
        format.json { render json: @team_membership.errors, status: :unprocessable_entity }
      end
    end
  end

谢谢!

2 个答案:

答案 0 :(得分:0)

您没有在视图中显示错误,请将其添加到new.html.erb中,然后根据需要设置样式

<% if @team_membership.errors.any? %>
  <ul>
    <% @team_membership.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
  </ul>
<% end %>

尝试一次!

答案 1 :(得分:0)

您可以检查这些

  • team_membership_params应该允许您要保存的列
  • TeamMembership模型根据需要进行验证(否则会在保存时引发错误)