Rails 多主键 erb 中 form_for 提示 missing required keys: [:id],我明白默认 ID 是主键,但我确实不能用它

newRer · 2017年09月18日 · 最后由 newRer 回复于 2017年09月18日 · 1516 次阅读

strategies 表的主键是 date 和 code,在 show.ERB 中,我已经拿到@strategy实体了,也可以访问@strategy.code,但是为什么 form_for 会提示 missing required keys: [:id] 呢?为什么还要 id,我必须要在 model 中显式声明主键么?该怎么声明。

model 实际上我没有定义任何方法:

class Strategy < ApplicationRecord


end

routes.rb

  get 'strategies/new'
  get 'strategies/show'
  get 'strategies/index'

resources :strategies

StrategiesController

def show
@strategy = Strategy.where("code = #{@code} and date=#{@date}").first
end

Strategies#show erb

<div>
  <%=@strategy.date%><br>#正常显示
  <%=@strategy.code%><br>#正常显示
</div>
<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@strategy) do |f| %>#missing required keys: [:id],这个erb中实际我已经得到@strategy的实体了,为什么还要id,我必须要在model中显式声明主键么?该怎么声明
        <%= f.label :code %>
        <%= f.text_field :code %>
        <%= f.label :date %>
        <%= f.text_field :date %>


        <%= f.submit "Create my account", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

我是由另一个表 dayline 跳转到 strategie 的,是一个 link,


<%=link_to image_tag("/a.jpg"), { :controller => 'strategies', :action => 'show' }, id: "getstategy"%>

code 和 date 都是动态的,触发这个 link 在 js 中是这样写的,和这里有关么?

$('.fkwebp').on('click', function (event) {
        const {code,baseDate,name,offsetDate} = getStockInfo(this,event);
        $("#getstategy").attr("href",`/strategies/show?code='${code}'&date='${offsetDate}'`);
        $("#getstategy img").click()
    });

主键名默认是 id,这是一种约定,如果需要改变主键名称可以这样

self.primary_key = :balabala
adamshen 回复

我已经在 Strategy 添加主键了,结果还是一样,问题是 erb 中已经能使用@strategy的实例成员了,为什么在 form_for 中不行

class Strategy < ApplicationRecord
  belongs_to :DayLine

  self.primary_key = 'code', 'date'
end

newRer 回复

主键只能有一个,你这条语句相当于设置主键为

"[\"code\", \"date\"]"
adamshen 回复

那么在 rails 中不能设置多主键么?

newRer 回复

数据库本来就只能存在唯一主键啊,还有你用 rails api 的时候不要想当然自己造语法,如果当黑盒来用,就应该只用例子上面的语法。

adamshen 回复

主键可以是联合主键

adamshen 回复

多主键是很正常的需求吧,而且这不能解释下面这段代码为什么第一行没问题,第二天就提示错误,

<%=@strategy.code%><br>#正常显示

<%= form_for(@strategy) do |f| %>#missing required keys: [:id]
nouse 回复

查了下,官方好像没有支持,不过可以用 Gem

https://github.com/composite-primary-keys/composite_primary_keys

adamshen 回复

我已经在 erb 中得到 model 实体了,不需要在查询阶段设置多主键了。而且这个 star 太少,不太敢用。 问题已经找到了,我看了 form_for 生成的源代码了,form_for 是个辅助方法,为了提交表单时唯一标识这个实体,所以 html form 里会用到这个实体的 id,我只要不用这个辅助方法,自己写 form 应该就没问题了,试试看

newRer 回复

这个报错信息应该是在自动生成 post url 的时候出的,你可以用 form_for 的 url option 显式指定 post action 的地址,试试看

adamshen 回复

我看了一下 form_for 的代码,终究还是需要 id,这时我想到我当前表也不大,所以就干脆给他一个 id 吧。

newRer 关闭了讨论。 09月18日 16:19
需要 登录 后方可回复, 如果你还没有账号请 注册新账号