我决定在Rails中克隆Facebook。首先,我正在努力让状态更新生效。我将它设置为由Pages控制器调用的StatusUpdate模型,以便在索引页面上呈现。
我遇到的问题是,如果我使用form_for(@status_update),我会得到:
undefined method to_key' for
<StatusUpdate::ActiveRecord_Relation:0x00000000049d3448>
Did you mean? to_set to_ary如果我使用form_with(model: @status_update)
undefined method to_model' for
<StatusUpdate::ActiveRecord_Relation:0x000000000471cd80>
Did you mean? to_xml如果我使用form_with(model: status_update)
undefined local variable or method status_update' for
<#<Class:0x0000000005801678>:0x0000000002ec8ec8>
Did you mean? @status_update我的行动:
def create
@status_update = StatusUpdate.new(status_update_params)
respond_to do |format|
if @status_update.save
format.html { redirect_to root_path, notice: 'Status successfully posted!' }
else
format.html { render :new }
end
end和erb视图:
<%= form_with(model: status_update) do |sp| %>
<div class="form-group">
<%= sp.label :status_update %>
<%= sp.text_area :status_update, class: 'form-control', rows: 15, placeholder: 'Content' %>
</div>
<div class="form-group">
<%= sp.submit 'Submit', class: 'btn btn-primary' %>
</div>
<% end %>发布于 2018-04-12 18:14:16
我认为你错过了初始化的步骤。您必须首先在控制器的new操作中初始化模型对象。
def new
@status_update = StatusUpdate.new
end然后在表单中使用它。
form_with(model: @status_update)发布于 2018-04-12 21:50:06
form_with的参数必须是单个模型实例。不是整个收藏。
class Pages
def index
@status_updates = StatusUpdate.all
@new_status_update = StatusUpdate.new
end
end
---
# app/views/pages/index.html.erb
<%= form_with(model: @new_status_update) %>
# ...
<% end %>
<%= @status_updates.each do |s| %>
# ...
<% end %>这就是为什么在命名变量时需要注意复数!
解决此问题的另一种方法是使用条件:
# app/views/status_updates/form.html.erb
<%= form_with(model: local_assigns(:status_update) || StatusUpdate.new) %>
...
<% end %>这样,即使没有StatusUpdate实例,也可以将表单用作部分表单:
# app/views/pages/index.html.erb
<%= render partial: 'status_updates/form' %>
<%= @status_updates.each do |s| %>
# ...
<% end %>https://stackoverflow.com/questions/49792239
复制相似问题