simple_form params ruby on rails; autofill resident variable

▼魔方 西西 提交于 2019-12-11 17:42:37

问题


When a user clicks "add attachment" from resident show page, i'd like to autocomplete the field resident on form. We already know what resident they would like to add the attachment.

On the show page button, I pass resident params and these params are visible in the form url. Although the field is not completed.

http://localhost:3000/app/attachments/new?resident_id=2

Link on residient show page:

<a href="<%= new_app_attachment_path(resident_id: @resident.id) %>" class="btn btn-block btn-default btn-sm">New attachment</a>

Resident model:

  class Resident < ApplicationRecord
  acts_as_paranoid

  has_many :appointments, dependent: :destroy
  has_many :care_plans, dependent: :destroy
  has_many :contacts, dependent: :destroy
  has_many :incidents, dependent: :destroy
  has_many :letters, dependent: :destroy
  has_many :sonas, dependent: :destroy
  has_many :tasks, dependent: :destroy
  has_many :activities, dependent: :destroy
  has_many :progress_notes, dependent: :destroy
  has_many :diagnosis_paragraphs, dependent: :destroy
  has_many :attachments, dependent: :destroy
  belongs_to :room, optional: true

  validates :first_name, presence: true, length: { maximum: 50 }
  validates :last_name, presence: true, length: { maximum: 50 }
  validates :date_of_birth, presence: true


  def full_name
    [first_name, middle_name, last_name].select(&:present?).join(' ').titleize
  end



end

Attachment form:

<%= simple_form_for([:app, @attachment]) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.association :resident, label_method: :full_name, prompt: "Choose a resident", collection: Resident.order(:first_name) %>
    <%= f.input :name %>
    <%= f.input :document %>
    <div class="form-group">
      <label>Author</label>
    <input class="form-control" type="text" placeholder="<%= @current_user.full_name %>" readonly value="<%= @attachment.author.try(:full_name) %>">
    </div>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

回答1:


On the attaachments#new action, capture the params and set the resident as follows

def new
  @resident = Resident.find(params[:resident_id])
end

Now, set the value as selected like so

<%= f.association :resident, label_method: :full_name, prompt: "Choose a resident", collection: Resident.order(:first_name), selected: @resident.id %>


来源:https://stackoverflow.com/questions/52434240/simple-form-params-ruby-on-rails-autofill-resident-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!