在补丁之前改变参数值

时间:2018-01-31 12:31:15

标签: ruby-on-rails ruby

我有一个显示外键值的表单中的texfield。现在我想更新值并将其保存到DB。这是代码:

表示我使用的表格:

  f.text_field :port, :value =>@entry.port.number, class:"form-
  control", placeholder:"Port" 

在控制器中我使用的是param方法:

def entry_params
  params.require(:entry).permit(:description,:rule_id, :protocol_id,   
  :url, :port)
end

更新方法如下所示:

def update
  @entry.url.name = params[:entry][:url]
  @entry.port.number = params[:entry][:port]
  if @entry.update(entry_params)
    flash[:success] = "Entry was successfully updated!"
    redirect_to entry_path(@entry)
  else
    render 'edit'
  end
end

但如果我想尝试保存它,则会显示以下错误:

Url(#70247237379440) expected, got "www.drive.google.com" which is an 
instance of String(#70247218839280)

现在我的问题是,(我对rails很新)我该如何解决这个问题?我知道它期望一个对象作为参数,但如果我改变这样的参数:

params[:url] = @entry.url

它不起作用。

1 个答案:

答案 0 :(得分:0)

我可以在这里考虑两种方法,具体取决于您希望实现的目标。

如果您希望根据字符串参数分配entry新的url,可以使用以下内容:

@entry.url = Url.find_by_name(params[:entry][:url])

根据您的模型设置,如果您的条目中有url_id列,最好使用select字段,将URL的名称和ID传递给选项。如果您可以将此信息添加到您的问题中,我可以根据需要更新/排除此信息。

如果您只是想通过条目的表单更新网址,那么您最好使用accepts_nested_attributes_for

这样做,您可以通过父表单直接更新关联的对象。如果这听起来像是适合您的方法,请告诉我,我可以提供更多详细信息:)

编辑:根据你的评论,听起来这是你想要的选择。所以,你需要以下内容:

<强> entry.rb

accepts_nested_attributes_for :url

表格形式:

...
f.nested_fields_for :url do |url_fields|
  url_fields.text_field :name
end
...

您需要更新控制器中的参数以接受这些嵌套字段。我不记得他们采取的确切方法,但它类似于:

def new / edit # whichever you're in 
  ...
  @entry.build_url unless @entry.url.present?
end

def entry_params
  params.require(:entry).permit(:description,:rule_id, :protocol_id,   
  :port, url_attributes: [:name])
end

(可能需要一个空数组或url_attributes的哈希值。)

然后直接更新关联的网址。仅供参考,如果您没有关联的网址,则需要在控制器中使用@entry.build_url构建网址。

希望这会有所帮助 - 如果您有任何问题/细节需要帮助澄清,请告诉我,我会根据需要进行更新。