【问题标题】:Filling additional form parameters from one input从一个输入中填充其他表单参数
【发布时间】:2018-07-05 06:18:00
【问题描述】:

我对 Rails 还很陌生,找不到任何关于如何执行此操作的信息。

目前,用户通过填写​​包含 URL、标题、内容等的表单来创建项目。

@resource = Resource.new(resource_params) 

。 . .

def resource_params
  params.require(:resource).permit(:title, :url, :content, :name, :tags_as_string)
end

我希望用户能够仅输入 URL,并使用 MetaInspector gem (https://github.com/jaimeiniesta/metainspector) 为其余参数生成输入,然后能够返回到创建的项目并编辑其内容手动。

有人能指出我正确的方向吗?我觉得我需要创建某种辅助方法,但这是我在项目中真正遇到的第一个编程。

【问题讨论】:

  • “我希望用户只能输入 URL” - 然后,您需要从新资源表单中删除除 url 之外的所有字段。在您的控制器操作create 中,仅允许参数中的:url
  • 您可以使用单独的表单(包含所有字段)来编辑资源,并为update 操作设置一组不同的允许参数。

标签: ruby-on-rails ruby-on-rails-5


【解决方案1】:

为了防止用户传递除url 之外的任何字段的值,您需要从新资源表单中删除除 url 之外的所有字段。

app/views/resources/new.html.erb

<%= form_for(@resource) do |f| %>
  <%= f.text_field :url %>
<% end %>

在您的控制器操作create 中,仅允许:url 在参数中。

app/controllers/resources_controller.rb

def create
  @resource = Resource.new(params.require(:resource).permit(:url))
  # Set other attributes using `metainspector`. See documentation for usage.

  if @resource.save
    redirect_to resources_path
  else
    render :new
  end
end

您可以使用单独的表单(包含所有字段)手动编辑资源,并为update 操作设置一组不同的允许参数。

app/views/resources/edit.html.erb

<%= form_for(@resource) do |f| %>
  <%= f.text_field :url %>
  <%= f.text_field :title %>
  <%= f.text_field :content %>
  <!-- Add other editable fields here -->
<% end %>

app/controllers/resources_controller.rb

before_action :fetch_resource, only: [:edit, :update]

def update
  if @resource.update_attributes(resource_params)
    redirect_to resources_path
  else
    render :edit
  end
end

private

def fetch_resource
  # Fetch `Resource` instance from database. Homework for you.
end

def resource_params
  params.require(:resource).permit(:title, :url, :content, :name, :tags_as_string)
end

注意:此代码未经测试。这只是为您提供有关如何进行的提示。您可能需要更改一些方法/字段名称以使其适合您的应用程序。

【讨论】:

  • 谢谢!我今晚试试这个。
  • 谢谢 Jagdeep,您为我指明了正确的方向。我对事情的思考过度,误解了模型对象创建的工作原理。我在想我可能必须在将参数提交给 Model.new(params) 之前修改参数
猜你喜欢
  • 1970-01-01
  • 2018-03-08
  • 2015-06-20
  • 2018-02-19
  • 2016-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
相关资源
最近更新 更多