我有这样的模式,并联系了很多人:通过:
class RailwayStation < ActiveRecord::Base
has_many :railway_stations_routes
has_many :routes, through: :railway_stations_routes
end
class Route < ActiveRecord::Base
has_many :railway_stations_routes
has_many :railway_stations, through: :railway_stations_routes
end
class RailwayStationsRoute < ActiveRecord::Base
belongs_to :railway_station
belongs_to :route
end我添加了列st_index
add_column :railway_stations_routes, :st_index, :integer对于路由中的索引站,但我不明白如何从路由视图表单更改它:
ul
- @route.railway_stations.each do |railway_station|
li = railway_station.title
= ????发布于 2015-10-09 21:48:56
首先,您需要更正模型和表的命名方案,以便它们遵循rails约定。
从命令行运行以下命令:
$ rails g migration RenameRailwayStationsRoute并将“db/迁移”中的迁移编辑为:
class RenameRailwayStationsRoute < ActiveRecord:Migration
def change
rename_table :railway_stations_route, :railway_station_routes
end
end 运行迁移
$ rake db:migrate重命名模型文件:
$ cd app/models
$ mv railway_stations_route.rb railway_station_route.rb或者如果您使用的是GIT
$ git mv railway_stations_route.rb railway_station_route.rb编辑模型以使用正确的命名:
class RailwayStation < ActiveRecord::Base
has_many :railway_station_routes
has_many :routes, through: :railway_station_routes
end
class RailwayStationRoute < ActiveRecord::Base
belongs_to :railway_station
belongs_to :route
end
class Route < ActiveRecord::Base
has_many :railway_station_routes
has_many :railway_stations, through: :railway_station_routes
end将关联记录添加到窗体
最简单的方法是使用simple_form gem。按照说明(并记住重新启动rails服务器)之后,添加以下表单:
<%= simple_form_for(@route) do |f| %>
<%= f.association :stations, collection: Station.all, name_method: :title %>
<% end %>没有简单的形式,您可以这样做:
<%= form_for(@route) do |f| %>
<%= f.collection_check_boxes(:stations_ids, Station.all, :id, :title) do |b|
b.label { b.checkbox checked: @route.stations_ids.include?(object.id) }
end %>
<% end %>添加-访问连接模型
不幸的是,没有任何直接的方式来访问连接模型的属性,从一个多到多的关系的一端。
这是因为Rails没有跟踪模型是从哪里加载的,至少不是以您想要的方式加载的。(确实如此-但相当复杂)。
解决这一问题的一种方法是:
class RoutesController < ApplicationController
def show
@route = Route.eager_load(railway_station_routes: :railway_station).find(params[:id])
end
end我们使用eager_load连接这两个模型,以便rails运行一个数据库查询并同时加载railway_station_routes和railway_station。
然后,您将遍历连接模型,而不是站点:
ul
- @route.railway_station_routes.each do |rs|
li
# note that you cannot both use = and have a body in HAML/Slim
p = "index: #{ rs.st_index }"
p = rs.railway_station.titlehttps://stackoverflow.com/questions/33047083
复制相似问题