我是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
谢谢!
答案 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)
您可以检查这些