因爲它看起來是新的,所以讓我添加一些上下文。
當您在dogs#show
頁面上時您正在調用表格。這確實不意味着你要硬編碼url
- 傳遞@pedigree
變量應該給滑軌的形式提交給pedigrees#create
所需的信息:
<%= form_for @pedigree do |d| %>
Select your dog:
<%= d.collection_select :dog_id, @dogs,:id, :dname, prompt: "Select your dog" %>
Select your dog relation to the dog from this profile:
<%= select_tag(:relation_name, options_for_select [['Sibling', 1], ['Parent', 2], ['Grandparent', 3],
['Great-grandparent', 4], ['Child', 5], ['Grandchild', 6], ['Great-grandchild', 7]]) %>
<%= d.submit 'Add Relation' %>
<% end %>
如果你有你的@pedigree
變盤,這應該送形式爲pedigrees#create
或pedigrees#update
(取決於您是否使用Pedigree.new
或Pedigree.find
設置變量)。
既然你通過部分調用的形式,我會強烈建議使用它只是當地變量:
#app/controllers/dogs_controller.rb
class DogsController < ApplicationController
def show
@dog = Dog.find params[:id]
@pedigree = ...
end
end
#app/views/dogs/show.html.erb
<%= render "pedigrees/form", locals: {pedigree: @pedigree} %>
#app/views/pedigrees/_form.html.erb
<%= form_for pedigree ...
這看似低效的開始,但是你要記住該partials是意味着可在您的應用程序的任何地方。在他們裏面使用@instance_variables
實際上是到antipattern的一半!
其他一些注意事項:
1.不要使用HTML的 「造型」
我看到使用<br>
和<p>
人創造HTML換行符。
雖然這個「有效」,但它是不正確的。事實上,它是徹頭徹尾的破壞性(特別是當你到達更大的應用程序時)。
HTML 應該被視爲標記(格式化只有); CSS是你需要什麼樣式:
<%= form_for @pedigree do |d| %>
<%= d.text_field :name %>
<%= d.text_field :type %>
<% end %>
這是你的HTML應該是什麼樣子,然後你可以使用following CSS to style it:
#app/assets/stylesheets/application.css
form input {
display: block;
margin: 3px 0;
}
如果您需要正當理由換行符(也許你」重新使用一個列表或其他東西),那麼通過一切手段,使用<br>
- 但從來沒有用它來創建邊緣/填充幻覺。
沒有別的,它會弄亂你的造型與響應接口等
-
2.許多一對多
我不知道你的Rails的水平,所以如果這對你來說太簡單了,我很抱歉。
我相信,如果你使用的many-to-many
關係,特別是has_many :through
你可以大規模提高這樣的:
#app/models/dog.rb
class Dog < ActiveRecord::Base
has_many :pedigrees
has_many :relations, through: :pedigrees
end
#app/models/pedigree.rb
class Pedigree < ActiveRecord::Base
belongs_to :dog
belongs_to :relation
end
#app/models/relation.rb
class Relation < ActiveRecord::Base
has_many :pedigrees
has_many :dogs, through: :pedigrees
end
這將允許你從單一通話填充@dog.pedigrees
或@dog.relations
。因此,而不必create
/edit
新的「開山鼻祖」的記錄,你就可以只是dog
工作:
#app/controllers/dogs_controller.rb
class DogsController < ApplicationController
def show
@dog = Dog.find params[:id]
end
def update
end
private
def dog_params
params.require(:dog).permit(:name, :relation_ids)
end
end
這將允許您使用以下:
#app/views/dogs/show.html.erb
<%= form_for @dog do |f| %>
<%= f.text_field :name %>
<%= f.collection_select :relation_ids, Relation.all, :id, :name %>
<%= f.submit %>
<% end %>
這應該允許你選擇你的狗的各種「關係」,自動創建Pedigree
記錄。
謝謝。我已將硬編碼/譜系改爲您在那裏的路徑。 – Zero