【发布时间】:2018-08-02 06:12:41
【问题描述】:
我有一个显示 Content 的 Rails 应用程序。每条内容都属于一个Source 和一个Source has_many Contents。每个 Source 由一个 name 和一个 domain 组成。
内容也属于Edition。我的应用程序设置方式是,在创建/编辑 Editions 的表单中,我使用 Cocoon gem 嵌套了 Contents 的表单字段。
内容的嵌套字段包括link 字段。我需要做的是检查 link 与 Sources 表中的各种 domains 并在新创建/编辑的内容上设置相关的 source_id。
我在想我可以在editions controller 中设置相关的source_id update 或create 操作。但是,由于我收到的唯一数据是带有嵌入式contents_attributes 散列的参数散列(它不包含对source_id 的引用,因为source 未在表单中设置),我该如何设置@987654339 @使用表单上提交的“链接”?
这是我在 editions_controller 上的创建和更新操作:
def create
@edition = Edition.new(edition_params)
respond_to do |format|
if @edition.save
format.html { redirect_to @edition, notice: 'Edition was successfully created.' }
format.json { render :show, status: :created, location: @edition }
else
format.html { render :new }
format.json { render json: @edition.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @edition.update(edition_params)
format.html { redirect_to @edition, notice: 'Edition was successfully updated.' }
format.json { render :show, status: :ok, location: @edition }
else
format.html { render :edit }
format.json { render json: @edition.errors, status: :unprocessable_entity }
end
end
end
这里是使用的参数:
def edition_params
params.require(:edition).permit(:date,
:clicks,
:product_id,
contents_attributes: [:id,
:heading,
:body,
:link,
:top_story,
:section_id,
:_destroy
]
)
end
我应该在带有 source_id 的表单上隐藏输入吗?或者这可以在控制器上完成吗?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-5 nested-forms cocoon-gem