我正在将健身Web应用程序作为项目的一部分。该项目有5个模型。用户,肌肉群,饮食,锻炼和膳食。关联在下面的代码上。到目前为止,我为用户提供了一个新页面和一个显示页面。我想将用户从显示页面重定向到muscle_group索引页面,该页面将列出人体内的所有肌肉。该用户显然有很多Muscle_Group,我想为所有肌肉组(二头肌,背部,腿部,胸部)的Musk_group索引页面设置种子。问题是,我需要使用该应用使用当前用户的user_id创建这些实例,而目前我还不知道该怎么做。希望我的简要说明有所帮助,下面是我的代码。
class User < ApplicationRecord
has_many :diets
has_many :muscle_groups
before_save { self.email = email.downcase }
#before saving, the email is lowercased
validates :name, presence: true, length: { maximum: 50 }
#validates the names presence, max char length is 50
validates :weight, presence: true, numericality: true
validates :height, presence: true, numericality: true
validates_inclusion_of :gender, :in => %w( m f male Male female Female)
validates :age, presence: true, numericality: {only_integer: true }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
end
class Muscle_Group < ApplicationRecord
has_many :workouts
belongs_to :user
end
class Diet < ApplicationRecord
belongs_to :user
has_many :meals
end
class Meal < ApplicationRecord
belongs_to :diet
end
class Workout < ApplicationRecord
belongs_to :muscle_group
end
class UsersController < ApplicationController
def new #render's the sign up page for a new user
@user = User.new
end
def create #action to create the user
@user = User.create(user_params)
if @user.save
log_in @user
flash[:success] = "Are you ready to GitFit?!"
redirect_to @user #redirects to the user's show page, which is the main menu
else
render 'new'
end
end
def show
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:name,
:email,
:weight,
:height,
:gender,
:age,
:password,
:password_confirmation)
end
end
class Muscle_GroupsController < ApplicationController
def index
@muscle_groups = Muscle_Group.all
end
end
答案 0 :(得分:2)
只需在种子文件中创建一个样本用户并将肌肉组关联到该用户。然后使用该帐户登录,您将获得结果。 例如这样的
numpy
我不知道您使用的确切字段和测量系统,但是看起来像这样。
另一种生产方式是注册成为网站用户。然后在控制台(# seed.rb
sample_user = User.create(name: "Joe", weight: 100, height: 180,
age: 23, email: "test@mail.com",
password: "123456")
MuscleGroup.create(user: sample_user, ...)
Diet.create(user: sample_user)
...
)中找到自己,并添加muscle_group和Diet等,然后将其手动连接到用户。