3

生成時間表腳手架。然後,在我的timetables_controller.rb中創建了一個新的動作「clas」。找不到'id'= clas的時間表

timetables_controller.rb

創建的form_for的行動 「CLAS」。需要選擇選項的值,PARAMS傳遞給控制器​​

clas.html.erb

<% form_for @classtimetable, :url => clas_timetables_path, :html => { :method => :post} do |f| %> 
<div class="field"> 
    <%= f.label "Select class" %> 
    <% values = ["1c", "2c", "3c", "4d", "5i"] %> 
    <%= f.select :clas, options_for_select(values) %> 
</div> 
<div class="actions"> 
    <%= f.submit "Submit"%> 
</div> 
<% end %> 

<% @classtimetable.each do |class_timetable| %> 
<%= class_timetable.day %> 
<% end %> 

的routes.rb

resources :timetables do 
member do 
    get 'clas' 
end 
end 

我需要讓所有的一天在我的clas.html.erb頁面中的類。從下拉菜單中選擇課程並提交即可完成。當我點擊提交時,值應該以params傳遞。 不知道如何解決它。有任何想法嗎?

+0

您能詳細說明何時發生錯誤嗎? –

+0

當我切換到URL「http:// localhost:3000 /時間表/分類」 – rinold

回答

2

添加控制器form_for標籤,

<% form_for @classtimetable, :url => { :controller => "your-controller-name", :action => :clas } do |f| %> 

或者你也可以直接這樣寫,

<% form_for @classtimetable, :url => clas_timetables_path, :html => { :method => :post} do |f| %> 

變化before_action一樣,

before_action :set_timetable, only: [:show, :edit, :update, :destroy, :clas] 

你會改變collectionmember和通過id

resources :timetables do 
member do 
    get 'clas' 
end 
end 
+0

仍然收到相同的錯誤 未定義的方法'model_name'的時​​間表:: ActiveRecord_Relation:類 – rinold

+0

現在出現錯誤無法找到沒有ID的時間表 – rinold

+0

找不到'id'= clas的時間表。 通過身份證是什麼意思? – rinold

0

試圖改變自己的form_tag這樣,

<% form_for @classtimetable, :url => clas_timetables_path(@classtimetable), :method => :post do |f| %> 
+0

嘗試過它。同樣的錯誤 – rinold

0

你能試試這個

def clas 
    @classtimetable = Timetable.where(timetable_params[:clas]).first 
end 
+0

不會修復... – rinold

+0

@rinold根據您的路線,您需要傳遞您的時間表id,因爲您的路線是成員 –

+0

該網址應該是'localhost:3000/timetables /:timetable_id/clas /' –

0

首先,我認識到:你在形式使用的路線獲取和發佈。所以這些行動不會匹配。 二:你寫的:

仍然得到了時間表:: ActiveRecord_Relation同樣的錯誤未定義的方法`MODEL_NAME」:類

所以看你怎麼定義@classtimetable

@classtimetable = Timetable.where(params[:clas]) 

這是一個關係,而不是ActiveRecord,你想通過clas找到。該錯誤將在這條線被拋出:

<% form_for @classtimetable, :url => clas_timetables_path, :html => { :method => :post} do |f| %> 

的form_for預計作爲第一個參數一個ActiveRecord或類似的東西(至少一些加載ActiveModel延伸::命名)。由於我沒有看到你對時間表的定義,我只是猜測,它有一個叫clas的屬性,你想找到clas等於表單中的選擇的時間表。因此,這將是:

@classtimetable = Timetable.find_by(clas: params[:clas]) 

什麼是一樣的:

@classtimetable = Timetable.where(clas: params[:clas]).first 

要獲得從關係的第一要素,您嘗試使用。

第三:由於您確實將路由定義爲成員路由,因此應該在clas_timetable_path中指定一個id。由於您在before_filter的clas action中加載了@timetable,因此我認爲您想要在那裏:

<% form_for @classtimetable, :url => clas_timetables_path(@timetable), :html => { :method => :get} do |f| %>