Rails显示另一个模型的错误消息

时间:2017-03-13 14:23:34

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

我有一个显示错误的html部分:

共享/ model_errors.html.erb

<% model.errors.full_messages.each do |msg| %>

我将它呈现在每个html文件的顶部,如

<%= render partial: 'shared/model_errors',locals: {model: @model_to_check_errors}%>

这对大多数人来说都很好。

让我们说我show.html.erb的{​​{1}}模板,我有ConversationsControllerform_tag提交邮件}。如果提交的消息为空,则MessagesController不允许保存该消息,因为它有验证错误。如果我无权访问MessagesController show.html.erb @message行为的create对象,如何在MessagesController中显示这些验证错误。有没有办法将错误消息添加到ConversationsController?它们将以这种方式显示。

编辑:

ConversationsController

的show.html.erb
<div class="container nav_exp">
  <%= render partial: 'shared/model_errors',locals: {model: @???}%>
  <div class="ch-body">
    <div class="col-md-12 bg-white ">
      <div class="chat-message">
        <ul class="chat" id="messages">
          <% if @messages != nil %>
            <%= render partial: 'conv_message', collection: @messages,:as => :message%>
          <% else %>
            <div class="panel-body hidden"></div>
          <%end%>
        </ul>
      </div>
      <%=form_tag(messages_path, :method=>'post',authenticity_token: true,remote: true) do%>
        <div class="chat-box bg-white">
          <div class="input-group">
            <%= text_field_tag :body,"", id:"message_body",class: "form-control border no-shadow no-rounded", placeholder: "Type your message here"%>
            <%= hidden_field_tag :conversation_id, @conversation.id %>
            <%= hidden_field_tag :receiver, @other.id %>
            <span class="input-group-btn">
              <%= submit_tag 'Submit', class: "btn btn-success no-rounded" %>
            </span>
          </div><!-- /input-group -->
        </div>
      <% end %>
    </div>
  </div>
</div>

create - MessagesController

messages_path方法
def create
    message = Message.new(message_params)
    message.user = current_user
    if message.save
      ...
    else
      puts 'not working'
     'I think 1 solution would be to add here flash messsages'
        end
      end

private

def message_params
  params.permit(:body, :conversation_id, :receiver)
end

0 个答案:

没有答案