Rails和验证

时间:2013-09-03 15:35:55

标签: ruby-on-rails-3 validation ruby-on-rails-4

我仍然(对于之前有帮助的人)在验证数据时遇到了问题。

情景

我有两个模型 - 用户住宿,每个用户都有一个住宿(has_one)。我可以使用current_user访问登录用户。

问题

当我在注册时验证用户时,一切正常,并且相应地为每个验证规则显示验证错误消息。但是,我现在正在尝试在输入时验证调整,我得到一个Rails错误页面:

未知行动

无法找到AccommodationsController

的动作'show'

但有趣的是,网址已更改为/ accommodation // edit,这似乎缺少住宿ID的ID(如果一切正常,我希望转移到编辑)。

我认为这不是验证规则本身,而是更多我如何处理重定向(这让我很难说实话!)。如果数据通过验证规则但是不能确定如何正常处理“非保存”,则数据会正确保存并正确重定向。

守则

住宿模式

class Accommodation < ActiveRecord::Base
  belongs_to :user

  #validation rules
  validates :user_id, presence: true
  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: {    case_sensitive: false }
end

/accommodations/new.html.erb

...
<%= form_for :accommodation, url: accommodations_path do |f| %>

<% if @accommodation.errors.any? %>
  <% @accommodation.errors.full_messages.each do |msg| %>
    <p class="error"><%= msg %></p>
  <% end %>
<% end %>

...

AccommodationsController(感谢@depa提供的帮助)

...
def index
  if current_user.accommodation.present?
    redirect_to edit_accommodation_path(current_user.accommodation)
  else
    redirect_to new_accommodation_path(current_user.accommodation)
  end
end

def new
  @accommodation = Accommodation.new
end

def create
  current_user.create_accommodation(accommodation_params)
  flash[:success] = "Accommodation details added"
  redirect_to edit_accommodation_path(current_user.accommodation)
end

def edit
end

def update 
  if @accommodation.update(accommodation_params)
    flash[:success] = "Accommodation details updated successfully"
    redirect_to edit_accommodation_path(@accommodation)
  else
    flash[:error] = "Accommodation details could not be updated"
    render 'edit'
  end
end

private
  def accommodation_params
    params.require(:accommodation).permit(:name, :email)
  end
...

2 个答案:

答案 0 :(得分:1)

优雅地处理失败的验证:

def create
  @accommodation = current_user.build_accommodation(accommodation_params)
  if @accommodation.save
    flash[:success] = "Accommodation details added"
    redirect_to edit_accommodation_path(current_user.accommodation)
  else
    flash.now.notice = "Error creating accommodation"
    render "new"
  end
end

答案 1 :(得分:0)

accommodation_params实际上是否设置了create?我希望您需要使用paramsparams[:accommodation]

如果不是,则create_accommodation来电将失败,这意味着current_user.accommodationnil,这可能会产生您的错误。