[英]How to submit a rails form before signup
我有一個與公司相關的任務模型。 我希望公司能夠在注冊主頁之前填寫表格以發布任務。 提交表單后,公司應該被重定向到注冊,然后任務會自動創建並與公司關聯。
我正在為公司模型使用設計。
靜態頁面控制器:
def home
end
任務控制器:
def create
@task = current_company.tasks.build(task_params)
if @task.save
redirect_to @task
else
render 'new'
end
end
def new
@task = Task.new
end
private
def task_params
params.require(:task).permit(:name, :description, :pay, files: [], course_ids: [])
end
任務模型:
belongs_to :company
公司型號:
has_many :tasks
任務/new.html.erb:
<h2>Create Task</h2>
</div>
<%= form_for(@task) do |f| %>
<div class="space">
<%= f.text_field :name, placeholder: "Task Name", class: "text-field" %>
</div>
<div class="space">
<%= f.text_area :description, placeholder: "Add Description", class: "text-field", rows: 10 %>
</div>
<div class="space">
<%= f.number_field :pay, placeholder: "Task Pay in USD", class: "text-field"%>
</div>
<div class="space">
<label class="file-field">
<%= f.file_field :files, multiple: true %>
</label>
</div>
<div class="space">
<%= f.submit "Post", class: "btn button", style: " width: 70%; padding-top: 10px; padding-bottom: 10px; margin-bottom: 10px; font-size: 1.25em;" %>
<% end %>
Static_pages/home.html.erb:
<div class="container-fluid container-1">
<div class="row col-centered">
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6" style="text-align: left;">
</div>
<div class="col-xs-5 col-sm-5 col-md-5 col-lg-5">
<h2 class="subtitle3"> Find Talented Freelancers</h2>
<%= link_to "Sign Up", companysignup_path, class: "btn button", style: "width: 40%; padding-top: 10px; padding-bottom: 10px; font-size: 1.25em; float: left;" %>
<%= link_to "Log In", companylogin_path, class: "btn button", style: "width: 40%; padding-top: 10px; padding-bottom: 10px; font-size: 1.25em; float: left; margin-left: 5%;" %>
</div>
</div>
</div>
一個非常常見的解決方案是提供“訪客帳戶”:
class AddStatusToCompanies < ActiveRecord::Migration[5.0]
def change
add_column :companies, :status, :integer, default: 0
end
end
class Company < ApplicationRecord
# ...
enum status: [:default, :guest, :registered]
validates :name, length: { minimum: 2 }, unless: :guest?
def password_required?
if guest?
false
else
super
end
end
end
這基本上只是一個帶有我們用來切換驗證的ActiveRecord::Enum的模型。
讓我們更改控制器以創建訪客記錄:
def create
@company = current_company || create_guest_company
@task = @company.tasks.build(task_params)
if @task.save
if @company.guest?
redirect_to "/your/registration/path"
else
redirect_to @task
end
else
render :new
end
end
private
def create_guest_company
company = Company.create!(status: :guest, email: "guest-#{SecureRandom.uuid}@example.com")
sign_in company
company
end
這還需要對您的注冊控制器進行大量更改,以支持更新現有記錄或創建單獨的路由和控制器來處理完整的訪客帳戶。 這是一個冗長教程的主題,而不是 stackoverflow 的答案。
您還需要一個經常性的后台任務來清理不完整的“轉換”(在該術語的營銷意義上)。
namespace :companies do
desc "Remove guest companies more than a week old."
task :cleanup => :environment do
Company.guest.where("created_at < ?", 1.week.ago).destroy_all
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.