DRY控制器。有效吗?使用simple_form进行创建和更新

时间:2016-08-09 17:13:04

标签: ruby-on-rails ruby validation simple-form dry

所以我得到了这些观点:

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>

这个型号: Place.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

但是,我正在尝试思考DRY并想知道是否有更好的方法来对名称地址和描述存在进行验证,而不会在我的控制器的创建和更新部分中使用相同的相同代码?我觉得我应该只写一次......

1 个答案:

答案 0 :(得分:0)

首先,您可以重构视图以使用以下结构:

# new.html.erb
<div class="booyah-box col-xs-10 col-xs-offset-1">
  <h1>Expose Your Hidden Gem</h1>
  <%= render 'form' %>
</div>

# edit.html.erb
<div class="booyah-box col-xs-10 col-xs-offset-1">
  <h1>Edit Your Place</h1>
  <%= render 'form' %>
</div>

# _form.html.erb
<%= simple_form_for @place do |f| %>
  <%= f.input :name %>
  <%= f.input :address %>
  <%= f.input :description %>
  <br />
  <% submit_label = @place.new_record? ? 'Create' : 'Update' %>
  <%= f.submit submit_label, class: 'btn btn-primary' %>
<% end %>

然后在你的控制器中你可以重构:

def create
  @place = current_user.places.new(place_params)
  if @place.save
    redirect_to root_path
  else
    render :new
  end
end

def update
  @place = current_user.places.find(params[:id])
  @place.attributes = place_params
  if @place.save
    redirect_to root_path
  else
    render :edit
  end
end