将当前对象的参数传递给create method Rails

时间:2018-02-13 01:46:58

标签: ruby-on-rails

而不必为嵌套属性创建单独的控制器,如:

def new
    @map = @account.maps.build
end

def create
    @map = @account.maps.create(params[:map].permit(:))
end

如何将account_id的参数传递给maps控制器中的create方法,而不是为accounts_maps创建一个完整的单独控制器?

例如:

如果我在此网址下创建地图:http://localhost:3000/accounts/1/maps/new 创建时,我需要地图的account_id为1。怎么能实现这一目标?

1 个答案:

答案 0 :(得分:1)

如果您在routes.rb

中定义了这样的路线
resources :accounts do
  resources :maps
end

网址为http://localhost:3000/accounts/17/maps,您可以使用

访问帐户ID
params[:account_id]

在这种情况下将是17。此外,@ account.maps.build会自动将account_id添加到地图中,您可能缺少的是声明@account。

在您的示例中,您可以执行

before_action :find_account

def new
  @map = @account.maps.build
end

def create
  @map = Map.create(map_params)
end

private

def find_account
  @account = Account.find(params[:account_id])
end

def map_params
  params.require(:map).permit(:name, :account_id) #permit all map params
end