1
所以我已經得到了這些觀點:DRY控制器。有效嗎?用於創建和更新使用simple_form
new.html.erb
<div class="booyah-box col-xs-10 col-xs-offset-1">
<h1>Expose Your Hidden Gem</h1>
<%= simple_form_for @place do |f| %>
<%= f.input :name, error: "Name is mandatory" %>
<%= f.input :address %>
<%= f.input :description %>
<br />
<%= f.submit 'Create', class: 'btn btn-primary' %>
<% end %>
</div>
edit.html.erb
<div class="booyah-box col-xs-10 col-xs-offset-1">
<h1>Edit Your Place</h1>
<%= simple_form_for @place do |f| %>
<%= f.input :name %>
<%= f.input :address %>
<%= f.input :description %>
<br />
<%= f.submit 'Update', class: 'btn btn-primary' %>
<% end %>
</div>
這種模式: 廣場。 rb
class Place < ActiveRecord::Base
belongs_to :user
has_many :comments, dependent: :destroy
has_many :photos
geocoded_by :address
after_validation :geocode
validates :name, presence: true
validates :address, presence: true
validates :description, presence: true
end
最後,places_controller.rb (只顯示創建和更新)
def create
@place = current_user.places.create(place_params)
if @place.save
redirect_to root_path
else
render :new
end
end
def update
@place = Place.find(params[:id])
if @place.user != current_user
return render text: 'Not Allowed', status: :forbidden
end
@place.update_attributes(place_params)
if @place.save
redirect_to root_path
else
render :edit
end
end
但是,我試圖想幹,想知道是否有更好的方法來做名稱地址和說明存在一個驗證,而不必在同一代碼相同我的控制器的創建和更新部分?我覺得我應該只是一次寫它......