首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >获得在不同控制器Rails下发布模型的能力

获得在不同控制器Rails下发布模型的能力
EN

Stack Overflow用户
提问于 2018-04-12 16:57:16
回答 2查看 102关注 0票数 0

我决定在Rails中克隆Facebook。首先,我正在努力让状态更新生效。我将它设置为由Pages控制器调用的StatusUpdate模型,以便在索引页面上呈现。

我遇到的问题是,如果我使用form_for(@status_update),我会得到:

代码语言:javascript
运行
复制
undefined method to_key' for
<StatusUpdate::ActiveRecord_Relation:0x00000000049d3448>
Did you mean? to_set to_ary

如果我使用form_with(model: @status_update)

代码语言:javascript
运行
复制
undefined method to_model' for
<StatusUpdate::ActiveRecord_Relation:0x000000000471cd80>
Did you mean? to_xml

如果我使用form_with(model: status_update)

代码语言:javascript
运行
复制
undefined local variable or method status_update' for
<#<Class:0x0000000005801678>:0x0000000002ec8ec8>
Did you mean? @status_update

我的行动:

代码语言:javascript
运行
复制
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视图:

代码语言:javascript
运行
复制
<%= 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 %>
EN

回答 2

Stack Overflow用户

发布于 2018-04-12 18:14:16

我认为你错过了初始化的步骤。您必须首先在控制器的new操作中初始化模型对象。

代码语言:javascript
运行
复制
def new
 @status_update = StatusUpdate.new
end

然后在表单中使用它。

代码语言:javascript
运行
复制
form_with(model: @status_update)
票数 1
EN

Stack Overflow用户

发布于 2018-04-12 21:50:06

form_with的参数必须是单个模型实例。不是整个收藏。

代码语言:javascript
运行
复制
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 %>

这就是为什么在命名变量时需要注意复数!

解决此问题的另一种方法是使用条件:

代码语言:javascript
运行
复制
# app/views/status_updates/form.html.erb 
<%= form_with(model: local_assigns(:status_update) || StatusUpdate.new) %>
  ...
<% end %>

这样,即使没有StatusUpdate实例,也可以将表单用作部分表单:

代码语言:javascript
运行
复制
# app/views/pages/index.html.erb
<%= render partial: 'status_updates/form' %>

<%= @status_updates.each do |s| %>
  # ...
<% end %>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49792239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档