我有这个模型和多对多关联:通过:
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
= ????
最佳答案 首先,您需要更正模型和表的命名方案,以便它们遵循rails约定.
从命令行运行:
$rails g migration RenameRailwayStationsRoute
并在“db / migrations”中编辑迁移以阅读:
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 %>
> https://github.com/plataformatec/simple_form#associations
> http://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes
添加 – 访问连接模型
从多对多关系的一端访问连接模型的属性没有任何不幸的直接方法.
这是因为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.title