Ruby Rails 使用关联排序
Ruby on Rails Order By Using Associations
我目前通过在 Rails 应用程序上处理我的 Ruby 来获得订单,以便用户可以在预订索引上通过 show_date
订购他们的预订。这是通过 bookings_controller 中的以下内容完成的:
def index
@bookings = Booking.joins(:showing).all.order(params.fetch(:sort, 'id asc'))
end
以及查看代码:
<form>
Order by:
<select name="sort">
<option value="show_date ASC">Show Date (Oldest First)</option>
<option value="show_date DESC">Show Date (Most Recent First)</option>
</select>
<button>
Go
</button>
</form>
但我想要做的是让用户能够按电影的标题和放映日期进行排序。我试图用这段代码来做到这一点:
views/bookings/index.html.erb:
<form>
Order by:
<select name="sort">
<option value="show_date ASC">Show Date (Oldest First)</option>
<option value="show_date DESC">Show Date (Most Recent First)</option>
<option value="title ASC">Film Title (A-Z)</option>
<option value="title DESC">Film Title (Z-A)</option>
</select>
<button>
Go
</button>
</form>
和 bookings_controller:
def index
@bookings = Booking.joins(:showing, :film).all.order(params.fetch(:sort, 'id asc'))
end
但这不起作用,我收到错误消息:
ActiveRecord::StatementInvalid in Bookings#index
SQLite3::SQLException: no such column: film:
SELECT "bookings".* FROM "bookings" INNER JOIN "showings" ON
"showings"."id" = "bookings"."showing_id" ORDER BY film ASC
我认为这是因为它们不是预订和电影之间的关联。
Booking.rb:
belongs_to :user
belongs_to :showing
delegate :screen, to: :showing
Showing.rb:
belongs_to :film
has_many :bookings
belongs_to :screen
Film.rb:
has_many :showings
belongs_to :certificate
belongs_to :category
试试这个:
Booking.joins(showing: :film).whatever
。
这可能会解决嵌套连接问题。
我目前通过在 Rails 应用程序上处理我的 Ruby 来获得订单,以便用户可以在预订索引上通过 show_date
订购他们的预订。这是通过 bookings_controller 中的以下内容完成的:
def index
@bookings = Booking.joins(:showing).all.order(params.fetch(:sort, 'id asc'))
end
以及查看代码:
<form>
Order by:
<select name="sort">
<option value="show_date ASC">Show Date (Oldest First)</option>
<option value="show_date DESC">Show Date (Most Recent First)</option>
</select>
<button>
Go
</button>
</form>
但我想要做的是让用户能够按电影的标题和放映日期进行排序。我试图用这段代码来做到这一点:
views/bookings/index.html.erb:
<form>
Order by:
<select name="sort">
<option value="show_date ASC">Show Date (Oldest First)</option>
<option value="show_date DESC">Show Date (Most Recent First)</option>
<option value="title ASC">Film Title (A-Z)</option>
<option value="title DESC">Film Title (Z-A)</option>
</select>
<button>
Go
</button>
</form>
和 bookings_controller:
def index
@bookings = Booking.joins(:showing, :film).all.order(params.fetch(:sort, 'id asc'))
end
但这不起作用,我收到错误消息:
ActiveRecord::StatementInvalid in Bookings#index
SQLite3::SQLException: no such column: film:
SELECT "bookings".* FROM "bookings" INNER JOIN "showings" ON
"showings"."id" = "bookings"."showing_id" ORDER BY film ASC
我认为这是因为它们不是预订和电影之间的关联。
Booking.rb:
belongs_to :user
belongs_to :showing
delegate :screen, to: :showing
Showing.rb:
belongs_to :film
has_many :bookings
belongs_to :screen
Film.rb:
has_many :showings
belongs_to :certificate
belongs_to :category
试试这个:
Booking.joins(showing: :film).whatever
。 这可能会解决嵌套连接问题。