我使用fields_for
与我的用户表构建关联表。一切似乎都运行正常,除非它将记录添加到数据库时它出现为零。
ERB
<%= form_for @user, url: users_path(@user), :method => :post do |f| %>
<%= f.label :name %>
<%= f.text_field :name, class: "form-control", placeholder: 'Name' %>
<%= f.label :email%>
<%= f.text_field :email, class: "form-control", placeholder: "Email" %>
<%= f.label :address%>
<%= f.text_field :address, class: "form-control", placeholder: "Address" %>
<%= f.label :phone %>
<%= f.text_field :phone, class: "form-control", placeholder: "Phone Number" %>
<%= f.label :resume %>
<%= f.file_field :resume %>
<%= f.label :cover_letter %>
<%= f.file_field :cover_letter %>
<% f.fields_for @userjob do |ff| %>
<% ff.hidden_field :user_id, :value => @user.id %>
<% ff.hidden_field :job_id, :value => @jobs.first.id %>
<% end %>
<%= f.submit "Apply"%>
<% end %>
用户模型
class User < ActiveRecord::Base
has_many :userjob
validates :name, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
mount_uploader :resume, ResumeUploader
mount_uploader :cover_letter, CoverLetterUploader
accepts_nested_attributes_for :userjob
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.oauth_token = auth.credentials.token
user.save!
end
end
end
工作控制器
def index
@jobs = Job.all
@user = User.new
@userjob = UserJob.new
end
用户控制器
def create
@user = User.new(user_params)
@userjob = UserJob.new(user_params[userjob_attributes:[:user_id, :job_id]])
if @user.save & @userjob.save
flash[:success] = "Thanks for applying!"
redirect_to root_path
else
render 'new'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :address, :phone, :resume, :cover_letter, userjob_attributes:[:user_id, :job_id])
end
end
分贝
=> #<ActiveRecord::Relation [#<UserJob id: 1, user_id: nil, job_id: nil
log params
parameters: {"utf8"=>"✓", "authenticity_token"=>"HLT46ditBHYcnAgOfZ7nfdDIP90EjNUdB+QB+3vjJOqnva6ZzVMXh0OiQte2v34aQ7opK8gPuk63fCTUVkJfBw==", "user"=>{"name"=>"test7", "email"=>"test7@test.com", "address"=>"", "phone"=>""}, "commit"=>"Apply"}
答案 0 :(得分:0)
尝试放置“<%=”,它们是隐藏字段,但必须“绘制”。
<%= f.fields_for @userjob do |ff| %>
<%= ff.hidden_field :user_id, :value => @user.id %>
<%= ff.hidden_field :job_id, :value => @jobs.first.id %>
<% end %>