加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – 被称为id为nil,这将错误地为4 – 如果你真的

发布时间:2020-12-17 07:10:01 所属栏目:百科 来源:网络整理
导读:我想知道是否有人可以帮助我.我现在正在学习ROR并遇到了一些麻烦. 我已经创建了other_users并使用scaffold发布了模型. other_users有很多:帖子等等. 我们的想法是,当用户登录并创建帖子时,show action会显示创建此帖子的用户的名称. ?我想知道是否有人可以
我想知道是否有人可以帮助我.我现在正在学习ROR并遇到了一些麻烦.
我已经创建了other_users并使用scaffold发布了模型. other_users有很多:帖子等等.
我们的想法是,当用户登录并创建帖子时,show action会显示创建此帖子的用户的名称.
?我想知道是否有人可以打电话给我.

后控制器

def new
    @post = Post.new(:other_user_id => @other_user.id)

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @post }
    end
  end
def create
    @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post,notice: 'Post was successfully created.' }
        format.json { render json: @post,status: :created,location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors,status: :unprocessable_entity }
      end
    end
  end

发布视图_form:

<%= form_for(:post,:url => {:action => 'create',:other_user_id => @other_user.id}) do |f| %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我知道这有点不对劲,但我对此很新,所以我无法自己解决这个问题

解决方法

在第2行,@other_user未知,所以它是零.我们试图从一个nil获取id,因此它会产生一个名为id为nil的错误.初始化@other_user并再试一次.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读