根据特定参数设置现有记录的嵌套属性

时间:2017-01-12 05:10:54

标签: ruby-on-rails ruby ruby-on-rails-4

我在这里的第一篇文章,所以我希望我收录所有必要的信息!很高兴我已经设法让它学习了两个月,而不必问任何问题。 : - )

我有一个带有嵌套商店记录的Callsheets记录,其中包含:lastvisit列,我希望每次每月提交一个新的Callsheet时更新该列。应该更新:lastvisit字段,其中Store:id == @ callsheet.store_id已经定义。我的初学者认为'update'方法的正确代码是

@callsheet.update(callsheet_params).where(@callsheet.store_id => @store.id)

但我不确定如何在这个实例中访问@store,这可能只会创建一个新记录。

对正确方向的任何帮助或要点表示赞赏。谢谢!

我一直试图让它在'update'方法中运行,但是如果有任何不同的话,我也想让它在'create'方法中运行。相关信息:

callsheet.rb:

class Callsheet < ActiveRecord::Base
  belongs_to :store
  accepts_nested_attributes_for :store

callsheets_controller.rb:

class CallsheetsController < ApplicationController

def update
@callsheet = Callsheet.find(params[:id])
    if @callsheet.update(callsheet_params)
      redirect_to callsheet_dashboard_path
    else
      render action: :edit
    end
end

def callsheet_params
  params.require(:callsheet).permit(:id, :user_id, :store_id, . . . , store_attributes: [:id, :lastvisit])

edit.html.erb:

      <%= form_for @callsheet, url: callsheet_path, remote: true, :html => { :multipart => true} do |f| %>
          <%= f.fields_for :store do |s| %>
            <%= s.text_field :lastvisit, :id => 'lastvisitHidden' %>
          <% end %>
        <%= f.hidden_field :store_id, :id => 'storeSelectHidden' %>

//

1 个答案:

答案 0 :(得分:0)

如果store_id上的callsheet列有一个&#34;外键&#34;,您可以在模型上写下这些关联:

#callsheet
belongs_to :store

#store
has_many :callsheets

然后在您的控制器操作中,@callsheet.update(callsheet_params)之后:

  @callsheet.store.update(last_visit: Time.now)

这是最简单的,也是我推荐的。 @callsheet.store返回商店实例(您始终需要跟踪您的变量是模型实例,模型查询还是数组。)

您也可以这样说,它只是展示了访问商店的另一种方式:

 Store.find_by(id: @callsheet.store_id).update(last_visit: Time.now)

find_by被称为&#34;查询方法&#34; (参见ActiveRecord query interface),但与大多数其他人不同,它返回实例而不是查询。 update仅在实例上可调用,并返回一个布尔值,指示保存是否成功。 update也会触发回调链 - 请参阅ActiveRecord Callbacks

另一种方法:

Store.where(id: @callsheet.store_id).update_all(last_visit: Time.now)

这使用.where查询方法,它返回一个查询(在这种情况下,你知道它将是一个元素),然后是update all查询方法(不会触发回调链)

最后一点令人困惑,我劝阻你不要使用它。原因是一个调用表只有一个存储,所以将它作为一个数组加载会产生误导。