Ruby on rails ';属于';与表格(u)的联系
这个问题是关于Rails中带有助手的新的表单。特殊情况是当表单用于属于另一个的模型时。这里有一些代码 Routes.rbRuby on rails ';属于';与表格(u)的联系,ruby-on-rails,Ruby On Rails,这个问题是关于Rails中带有助手的新的表单。特殊情况是当表单用于属于另一个的模型时。这里有一些代码 Routes.rb resources :contents do resources :translations end 迁移 class CreateTranslations < ActiveRecord::Migration[5.2] def change create_table :translations do |t| t.text :translat
resources :contents do
resources :translations
end
迁移
class CreateTranslations < ActiveRecord::Migration[5.2]
def change
create_table :translations do |t|
t.text :translation
t.string :to_lang
t.references :content, foreign_key: true, dependent: :delete
t.timestamps
end
end
end
问题
这段代码似乎有效,但我认为我可以改进它。在创建操作中查看参数时,我看到:
<ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"dFdTw+d85qA2BsLb0OW4TcaVfkMIaNEYgXcPvE8ff5ANprfoL58clGlx5kSC5zzoSOM0nSf9kaNvH8ebpUj5JQ==", "translation"=>{"to_lang"=>"en"}, "commit"=>"Create Translation", "controller"=>"translations", "action"=>"create", "content_id"=>"1"} permitted: false>
@content = Content.find(params[:content_id])
@translation = @content.translations.build(translation_params)
<%= form_with(model: @translation, url: [@content, @translation], local: true) do |form| %>
您的
内容\u id
不在Rails设计的翻译哈希中。但是,您可以执行以下操作来稍微清理一下
class TranslationsController < ApplicationController
before_action :set_content, only: [:new, :create]
def new
@translation = @content.translations.new
end
def create
@translation = @content.translations.build(translation_params)
...
end
private
def set_content
# use params.require to use strong params
@content = Content.find(params.require(:content_id))
end
end
class TranslationController
如果您在其他操作中使用
@content
,只需在执行操作之前相应地调整过滤器即可谢谢,这很有帮助。我们如何知道这是预期设计?据你所知,原因是什么?嗯,如果你阅读Rails路由,从外到内,路径中的任何引用变量都将其显示为顶级params元素。文档中至少包含了5个示例,包括:-我不确定推理,但它是一致的,并且假设在路由路径中没有关系
<%= form_with(model: @translation, url: [@content, @translation], local: true) do |form| %>
class TranslationsController < ApplicationController
before_action :set_content, only: [:new, :create]
def new
@translation = @content.translations.new
end
def create
@translation = @content.translations.build(translation_params)
...
end
private
def set_content
# use params.require to use strong params
@content = Content.find(params.require(:content_id))
end
end