2016-01-23 152 views
2

嘗試將參數從url保存到數據庫中。Rails 4沒有用這種方法保存到數據庫中?

我有一個鏈接:

- @kits.each do |kit| 
    = link_to 'Submit Video', new_challenge_path(kit: kit) 
    #this will append a new parameter into the url 

的鏈接進入到一個表單頁面與此:

= simple_form_for @challenge, html: { class: "form-horizontal" } do |f| 
    = f.input :video_title 
    = f.input :video_url 
    = f.input :video_desc, as: :text 
    = f.button :submit, "Upload video" 

在我的控制,我有這樣的:

def create 
    @challenge = Challenge.new(challenge_params) 
    @challenge.kit_id = params[:kit] 

    respond_to do |format| 
    if @challenge.save 
     format.html { redirect_to @challenge, notice: 'Challenge was successfully created.' } 
     format.json { render :show, status: :created, location: @challenge } 
    else 
     format.html { render :new } 
     format.json { render json: @challenge.errors, status: :unprocessable_entity } 
    end 
    end 
end 

private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_challenge 
    @challenge = Challenge.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def challenge_params 
    params.require(:challenge).permit(:video_title, :video_url, :video_desc, :kit_id) 
    end 

之間的關聯套件和挑戰

class Challenge < ActiveRecord::Base 
    belongs_to :kit, counter_cache: true 
end 

class Kit < ActiveRecord::Base 
    has_many :challenges 
end 

該參數不保存到:kit_id。不是這樣的:@challenge.kit_id = params[:kit]應該照顧好它嗎?

+0

'Kit'和'Challenge'之間有什麼關聯? –

+0

@OlegSobchuk我已更新帖子以在兩者之間添加關聯 – hellomello

+0

new_challenge_path進入控制器的新方法,因此您的@ challenge.kit_id = params [:kit]應粘貼到您的新方法中。 – beck03076

回答

1

你是對的做kit_id控制器,而不是形式,因爲這樣做的形式(即使通過使用隱藏領域)是不安全的,因爲改變一個hidden_​​field的值只是一個檢查頁面元素的問題。

你在做什麼錯,我假設params[:kit]只是nil。您可能想要使用params[:kit_id]

如果不幫忙,把binding.pry這裏:

# ... code omitted 
    @challenge.kit_id = params[:kit] 
    binding.pry 
    # ... code omitted 

,並檢查params在打開控制檯中的價值。

+0

如果我使用'params [:kit_id]',那麼這是否意味着我需要改變我的鏈接,這樣的網址將''kit_id ='? – hellomello

+0

此外,我剛剛添加'binding.pry'到我現有的代碼,但我只是有一個錯誤:'未定義的方法'pry'' – hellomello

+0

另外,我在看控制檯,它顯示'kit_id'參數,但它不會在'INSERT INTO'挑戰中顯示'' – hellomello

相關問題