【发布时间】:2023-01-12 18:40:14
【问题描述】:
我想在创建记录时创建与另一个模型的关联。
这些模型通过关联使用 has_many。
楷模
食谱
class Recipe < ApplicationRecord
attribute :name
attribute :published
has_many :ingridients, dependent: :destroy
has_many :instructions, dependent: :destroy
has_many :recipe_seasons
has_many :seasons, through: :recipe_seasons
accepts_nested_attributes_for :recipe_seasons
validates_presence_of :name
end
季节
class Season < ApplicationRecord
has_many :recipe_seasons
has_many :recipes, through: :recipe_seasons
end
食谱季节
class RecipeSeason < ApplicationRecord
belongs_to :recipe
belongs_to :season
validates_presence_of :recipe
validates_presence_of :season
accepts_nested_attributes_for :season
end
控制器
def new
@month = 1
@recipe = Recipe.new
@recipe.recipe_seasons.build(season_id: @month).build_recipe
end
def create
@recipe = Recipe.new(recipe_params)
@recipe.save
redirect_to recipes_path
flash[:notice] = I18n.t("recipe.created")
end
private
def recipe_params
params.require(:recipe)
.permit(:name, :published, recipe_seasons_attributes:[:recipe_id, :season_id ])
end
创建食谱后,我希望使用新创建的食谱的 ID 将默认值 @month 插入到表 recipe_seasons 的记录中。
形式
<%= form_with(model: @recipe) do |f| %>
<%= f.label :name %>
<%= f.text_field :name, required: true %>
<%= f.label :published %>
<%= f.check_box :published, class: "form-control", placeholder: "Tick if done" %>
<%= f.submit %>
<% end %>
<%=link_to t("back"), recipes_path %>
当我创建一个食谱时,我希望同时将一条记录插入到 recipe_seasons 中,使用在食谱上创建的 id 作为表 recipe_seasons 上的 recipe_id。现在,我将对用于 season_id 的@month 的值进行硬编码。
【问题讨论】:
标签: ruby-on-rails activerecord associations