Создать из другого представления контроллеров с проверкой - PullRequest
0 голосов
/ 21 сентября 2018

Я пытаюсь создать агентов из моего выставленного счета.Я не могу показать ошибки проверки в моей форме, я могу только их прошить.Я пытался сделать форму только с @agent, чтобы отобразить, а не перенаправить, передать идентификатор счета в форме ... но я не понимаю.Как я могу создать агент и вернуться к представлению счета-фактуры с моими ошибками проверки в форме?

CONTROLLERS

bills_Controler.rb

def show
    @bill = Bill.find(params[:id])
    @agent = @bill.agent || Agent.new
    respond_to do |format|
      format.html 
      format.pdf do
        render pdf: @bill.to_filename
              end
      format.zip { send_zip }
    end
end

agents_controller.rb

def create
    @agent = Agent.new
    @bill=Bill.find(params[:bill_id])

    if build_agent(agent_params).save
        flash[:notice] = t('agent.saved')
            redirect_to bill_path (params[:billid])
    else
        #flash[:error] = @agent.errors
        #render 'bills/show'
        redirect_to bill_path(@bill), :flash => { :error => @agent.errors.full_messages.join(', ') }
    end
end

VIEWS

_bill.html.erb

<%= render 'bills/show/agents'%>

_agents.html.erb

<%= simple_form_for [@bill, @agent] do |f| %>
    <%= f.input :name, wrapper_html: { class: 'medium' } %>
    <%= f.input :surname, wrapper_html: { class: 'medium' } %>
    <%= f.input :phone_number, wrapper_html: { class: 'medium' }  %>
    <%= f.button :submit, class: 'button btn-main btn btn-primary'%>
<%end%>

МОДЕЛИ

bill.rb

belongs_to :agent, inverse_of: :bills

agent.rb

has_many :bills, inverse_of: :agents, dependent: :restrict_with_error
validates :name ,presence: true ....

МАРШРУТЫ

resources :bills, only: [:index, :show, :new, :create, :update] do
    resources :agents, only: [:new, :update,:create]
end

1 Ответ

0 голосов
/ 21 сентября 2018

Для отображения ошибок в полях необходимо render show действие с тем же объектом, который содержит ошибки:

def show
  # show action code goes here
end

def create
  @agent = Agent.new(agent_params)
  @bill = Bill.find(params[:bill_id])

  if @agent.save 
    # validation fails and  
    # the @agent object contains errors
    @bill.agent = @agent
    flash[:notice] = t('agent.saved')
    redirect_to bill_path(params[:bill_id])
  else
    render :new
    # because the new action contains a form
  end
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...