根据共享 has_one 关联有条件地分配控制器的实例变量
Conditionally assigning a controller's instance variable based on a shared has_one association
我有一个 Board
模型属于 Artist
或属于 has_one
关系中的 Album
:
class Artist < ActiveRecord::Base
has_one :board
end
class Album < ActiveRecord::Base
has_one :board
end
class Board < ActiveRecord::Base
belongs_to :artist
belongs_to :album
end
这也反映在我的路线中:
resources :artists do
resource :board, only: :show
end
resources :albums do
resource :board, only: :show
end
当我需要为 artists/1/board
或 albums/1/board
分配一个实例变量时,问题就出现了。我想根据 params[:artist_id]
或 params[:album_id]
分配值,但这似乎不起作用:
class BoardsController < ApplicationController
def show
params[:artist_id] ? @board = Board.find(params[:artist_id]) : @board = Board.find(params[:album_id])
end
end
完成此任务的最佳方法是什么?
def show
@board = params[:artist_id].present? ? Artist.find(params[:artist_id]).board : Album.find(params[:album_id]).board
end
我有一个 Board
模型属于 Artist
或属于 has_one
关系中的 Album
:
class Artist < ActiveRecord::Base
has_one :board
end
class Album < ActiveRecord::Base
has_one :board
end
class Board < ActiveRecord::Base
belongs_to :artist
belongs_to :album
end
这也反映在我的路线中:
resources :artists do
resource :board, only: :show
end
resources :albums do
resource :board, only: :show
end
当我需要为 artists/1/board
或 albums/1/board
分配一个实例变量时,问题就出现了。我想根据 params[:artist_id]
或 params[:album_id]
分配值,但这似乎不起作用:
class BoardsController < ApplicationController
def show
params[:artist_id] ? @board = Board.find(params[:artist_id]) : @board = Board.find(params[:album_id])
end
end
完成此任务的最佳方法是什么?
def show
@board = params[:artist_id].present? ? Artist.find(params[:artist_id]).board : Album.find(params[:album_id]).board
end