我有兩個表 - positions
表,其中的字段爲id
,position_id
,first_name
和last_name
。另一張表是positionslist
,字段爲id
,positions
。我將如何加入這兩張表? 這裏是我的positionscontroller:如何在rails上使用ruby連接兩個表
class PositionsController < ApplicationController
def index
#@positions = Position.all(:order=>'updated_at DESC')
@positions = Position.joins(:positions => :positionlists)
end
def new
@position = Position.new
end
def create
@position = Position.new(params.require(:position).permit(:position_id, :first_name, :last_name))
if @position.save
redirect_to(:controller=>'positions')
else
render 'new'
end
end
def edit
@position = Position.find(params[:id])
end
def update
@position = Position.find(params[:id])
if @position.update(params.require(:position).permit(:position_id, :first_name, :last_name))
redirect_to(:controller=>'positions')
else
render 'edit'
end
end
def destroy
@position = Position.find(params[:id])
@position.destroy
redirect_to(:controller=>'positions')
end
end
我的模型position.rb
class Position < ActiveRecord::Base
has_many :positionlists
has_many :positionlists , :through => :positions
validates :first_name, length: { in: 4..20}
validates :last_name, length: { in: 4..20}
end
我的模型positionlists.rb
class Positionlists < ActiveRecord::Base
has_many :positions
end
任何我的志願服務崗位index.html.erb
<% content_for :title, "Positions" %>
<%= render "layouts/nav" %>
<div class="clear"></div>
<h1>Positions List</h1>
<%= link_to "Add", new_position_path, :class =>'btn btn-success' %>
<br />
<br />
<table class="table">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Position</th>
<th>Options</th>
</tr>
<% @positions.each do |positions| %>
<tr>
<td><%= positions.first_name %></td>
<td><%= positions.last_name %></td>
<td><%= positions.position_id %></td>
<td>
<%= link_to "Edit", edit_position_path(positions)%> |
<%= link_to "Delete", position_path(positions),
method: :delete, data:{confirm: 'Are you sure you want to delete this?.' }%>
</td>
</tr>
<% end %>
</table>
非常感謝任何幫助!謝謝
在'Positionlists.rb'模型中,你的意思是'belongs_to:position'?另請注意單數用法。它是':position'而不是':positions'。你能解釋你想做什麼嗎? –
即時通訊試圖加入這兩個表中的表位置和表位置列表 – bobcatnyxz
您是否使用導軌移動或手動創建這些表? –