嘗試將參數從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]
應該照顧好它嗎?
'Kit'和'Challenge'之間有什麼關聯? –
@OlegSobchuk我已更新帖子以在兩者之間添加關聯 – hellomello
new_challenge_path進入控制器的新方法,因此您的@ challenge.kit_id = params [:kit]應粘貼到您的新方法中。 – beck03076