Rails在表单提交上从父表中为子表分配值

时间:2015-08-01 20:29:15

标签: ruby-on-rails

我有一个表单来创建“访问”,它们属于“分支”。我可以为每次访问分配branch_id,但是如何将“分支”中的其他字段分配给“访问”?例如,我想将branches_name字段添加到访问表中,而无需用户在表单中选择此值。我可以使用像“before_save”这样的东西吗?我可以使用collection_select字段保存branch_name以及branch_id吗?

branches_controller.rb:

class BranchesController < ApplicationController

  def new
   @branches = Branch.new
    @users = User.all
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @branch }
    end
  end

  def create
    @branches = Branch.new(branch_params)
    @branches.user_id = current_user.id if current_user
    if @branches.save
        redirect_to main_app.user_path(current_user)
    end
  end

  def show
    @branch = Branch.find(params[:id])
    @visits = Visit.where(branch_id: @branch.id)

    respond_to do |format|
      format.html
      format.js
    end
  end

  def show_visits
    @branch = Branch.find(params[:branch_params])
    @visits = Visit.where(branch_id: @branch.id)
  end

  private

  def set_branch
    @branch = Branch.find(params[:id])
  end

  def branch_params
    params.require(:branch).permit(:branch_name, :photo, :first_name, :last_name, :telephone_number, :contact_email, :address_line_1, :address_line_2, :city, :postcode)
  end

end

visits_controller.rb:

class VisitsController < ApplicationController
  before_filter :authenticate_user!, except: [ :new]
  before_action :set_visit, only: [:show, :edit, :update, :destroy]

  def index
    @visits = Visit.all
    @visits_by_date = @visits.group_by(&:date_from)
    @date = params[:date] ? Date.parse(params[:date]) : Date.today
    @users = User.all
  end

  def show
  end

  def new
    @visit = Visit.new
    @branch = Branch.all
  end

  def edit
  end

  def create
    @visit = current_user.visits.new(visit_params)
    respond_to do |format|
      if @visit.save
        format.html { redirect_to @visit, notice: 'Visit was successfully created.' }
        format.json { render :show, status: :created, location: @visit }
      else
        format.html { render :new }
        format.json { render json: @visit.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @visit.update(visit_params)
        format.html { redirect_to @visit, notice: 'Visit was successfully updated.' }
        format.json { render :show, status: :ok, location: @visit }
      else
        format.html { render :edit }
        format.json { render json: @visit.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @visit.destroy
    respond_to do |format|
      format.html { redirect_to visits_url, notice: 'Visit was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_visit
      @visit = Visit.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def visit_params
      params.require(:visit).permit(:location, :date_from, :time_from, :date_to, :time_to, :comment, :branch_id, :user_id)
    end
end

branch.rb:

class Branch < ActiveRecord::Base

  belongs_to :user
  has_many :visits

  mount_uploader :photo, PhotoUploader

  before_save :capitalize_attributes

  def capitalize_attributes
         capitalizable = ["first_name","last_name", "city", "branch_name"]
     self.attributes.each do |attr,val|
       #based on comment either of these will work
       #if you want to store nil in the DB then
       self.send("#{attr}=",val.strip.capitalize) if capitalizable.include?(attr) && !val.nil?
       #if you want to store a blank string in the DB then 
       self.send("#{attr}=",val.to_s.strip.capitalize) if capitalizable.include?(attr)
     end
   end

 def branch_name_select
   "#{branch_name}, #{address_line_1}, #{address_line_2}, #{city}, #{postcode}"
 end

end

visit.rb:

class Visit < ActiveRecord::Base
    belongs_to :branch  
    belongs_to :user #:as => 'created_by' 
    validates_uniqueness_of :time_from, :scope => [:date_from, :location], :message=>"slot is already taken on selected date"

end

_form.html.erb:

<% if user_signed_in? && current_user.user_type == 'client' %>


<%= form_for @visit do |f| %>
  <% if @visit.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@visit.errors.count, "error") %> prohibited this visit from being saved:</h2>

      <ul>
      <% @visit.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :branch_id, "Please Pick Service Provider/Branch you would like to visit:" %><br>
    <%= f.collection_select(:branch_id, Branch.all, :id, :branch_name_select, {prompt: "Select the Branch/Service"}, {:required => true}) %>
  </div>
  <div class="field">
    <%= f.label :date_from, "Please Pick Visit Date From:" %><br>
    <%= f.text_field :date_from, :required => true %>
  </div>
  <div class="field">
    <%= f.label :time_from, "Please Pick Visit Start Time:" %><br>
    <%= f.time_select :time_from, {:start_hour => 9, :end_hour => 20, :minute_step => 15,  :ampm => true}, :required => true %>
  </div>
  <div class="field">
    <%= f.label :date_to, "Please Pick Visit Date To:" %><br>
    <%= f.text_field :date_to %>
  </div>
  <div class="field">
    <%= f.label :time_to, "Please Pick Visit End Time:" %><br>
    <%= f.time_select :time_to, {:start_hour => 9, :end_hour => 20, :minute_step => 15, :ampm => true} %>
  </div>
  <div class="field">
    <%= f.label :comment, "If you have any specific requirements for your visit please let us now and leave the comment below:" %><br>
    <%= f.text_area :comment %>
  </div>

  <div class="field">
    <%= f.label :user_id %><br>
    <%= f.hidden_field :user_id, :value => current_user.id %>
  </div>

  <div class="actions">
    <%= f.submit "Submit Visit Request"%>
  </div>
<% end %>

<% end %>

0 个答案:

没有答案