Ruby on Rails - Pass ID from another controller

时间:2017-10-12 09:50:21

标签: ruby-on-rails ruby model controller associations

I have two models. First is Taxirecord and second is Carpark. Each Taxirecord may have its own Carpark. I have a problem with passing taxirecord_id to Carpark record. I have route

car_new GET    /taxidetail/:taxirecord_id/carpark/new(.:format) carparks#new

And i want to pass :taxirecord_id, which is id of taxirecord that im editing, to my create controller. My carpark model:

class Carpark < ActiveRecord::Base
    belongs_to :taxirecord
end

In controller im finding taxirecord_id by find function based on param :taxirecord_id, but id is nil when create is called. Can you please help me to find out what Im doing wrong and how Can I solve this problem? Thanks for any help!

My carpark controller

class CarparksController < ApplicationController
    def new
            @car = Carpark.new
    end
    def create
            @car = Carpark.new(carpark_params, taxirecord_id: Taxirecord.find(params[:taxirecord_id]))
            if @car.save
                    flash[:notice] = "Zaznam byl ulozen"
                    redirect_to root_path
            else
                    flash[:notice] = "Zaznam nebyl ulozen"
                    render 'new'
            end

    end
private def carpark_params
                params.require(:carpark).permit(:car_brand, :car_type, :driver_name, :driver_tel)
        end

end

3 个答案:

答案 0 :(得分:0)

我倾向于使用类似的东西:

before_action :assign_taxirecord   

...

private

def assign_taxirecord
  @taxirecord = TaxiRecord.find(params[:taxirecord_id])
end

然后在创建动作中:

def create
  @car = @taxirecord.build_carpark(carpark_params)
  ...
end 

显然,你的要求需要一点剪裁(即调用before_action的行为),但我希望有所帮助!

答案 1 :(得分:0)

无需发送taxirecord ID。

class Carpark < ApplicationRecord
  belongs_to :taxirecord
end


class Taxirecord < ApplicationRecord
  has_one :carpark
end

Rails.application.routes.draw do
  resources :taxirecords do 
    resources :carparks
  end
end


for new taxirecord
 t = Taxirecord.new(:registration => "efgh", :description =>"test")

for new carpark
 t.create_carpark(:description=>"abcd")


#=> #<Carpark id: 2, taxirecord_id: 2, description: "abcd", created_at: "2017-10-12 10:55:38", updated_at: "2017-10-12 10:55:38">

答案 2 :(得分:0)

我终于明白了 我添加了<%=link_to 'New Carpark', {:controller => "carparks", :action => "new", :taxirecord_id => @taxi_record.id }%> 到我的taxirecord表格和停车场表格<%= hidden_field_tag :taxirecord_id, params[:taxirecord_id] %> 和我的停车场管制员:@carpark.taxirecord_id = params[:taxirecord_id] 感谢大家的大力支持和帮助!