Rails 4 +设计。
想象一下,我们有一些实体形式。有用户字段名称,电子邮件,未登录用户的密码和实体中的少数字段(对于已登录的用户,没有名称/电子邮件/密码字段)。换句话说,我需要将两个动作(注册和发布问题)合二为一。如何在后端(控制器)内解决这个问题?
UPD 从控制器/视图添加了一些代码,但不认为它会有所帮助。
questions_controller.rb
class QuestionsController < ApplicationController
def index
@questions = Question.all
end
def new
@user = User.new unless user_signed_in?
@question = Question.new
render "new"
end
end
new.html.slim
= form_for @question do |f| # Don't know how to combine form for user and question
- unless user_signed_in?
= text_field @user, :name
= text_field @user, :email
= text_field @user, :password
= f.text_field :title
= f.text_area :summary
答案 0 :(得分:1)
在QuestionsController
中,您可以先设置一些逻辑来创建用户,然后使用创建的用户登录。最后处理问题的创建。
def create
# Permit the strong parameters as you're using rails 4
params.require(:question).permit(:title, :summary)
params.require(:user).permit(:name, :email, :password)
logged_in = false #initialize a logged_in flag
if user_signed_in?
logged_in = true #set the flag to true if logged in.
else
@user = User.new(params[:user])
if @user.save
sign_in(@user) #sign in the user if the creation was a success
logged_in = true #set the flag to true if the user created.
end
end
if logged_in
@question = current_user.questions.new(params[:question])
if @question.save
redirect_to questions_path #put in your logic after successful creation of question
else
render :new
end
else
render :new
end
end
您需要更改new.html.slim
以构建我们上面使用的确切参数。
= form_for @question do |f|
- unless user_signed_in?
= text_field :user, :name
= text_field :user, :email
= text_field :user, :password
= f.text_field :title
= f.text_area :summary
答案 1 :(得分:1)
您可以使用rails nested attributes接受参数。 在User和Question模型之间添加嵌套属性关系
class QuestionsController < ApplicationController
def new
@user = current_user || User.new
@question = @user.questions.new
render "new"
end
def create
user_params = params['user']
question_params = user_params.delete('questions_attributes')['0']
@user = current_user || User.new(user_params)
@question = @user.questions.new(question_params)
if @user.valid? && @question.valid?
@user.save && @question.save
sign_in(@user)
redirect_to :index
else
render 'new'
end
end
end
= form_for @user do |user|
- unless user_signed_in?
= user.text_field :name
= user.text_field :email
= user.text_field :password
= user.fields_for :questions do |question|
= question.text_field :title
= question.text_area :summary