我有这个模型和关联多对多:通过:
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
对于 route 的索引站,但我不明白如何从路线 View 表单中更改它:
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
关于ruby-on-rails - 访问 has_many 中的连接模型属性 : though relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33047083/