【问题标题】:has_many and belongs_ association rails 4has_many 和 belongs_ 关联 rails 4
【发布时间】:2014-11-12 10:26:26
【问题描述】:

我正在学习如何在 rails 4 应用程序中使用关联 我有一个用户有很多意见,我想在图书展示页面中添加用户意见 我就是这样进行的:

我的用户.rb

class User < ActiveRecord::Base
 has_one :panier
 has_many :opinions
end

意见.rb

class Opinion < ActiveRecord::Base
 belongs_to :user
end

views/books/show.html.erb

<h2>Votre opinion nous intéresse:</h2>

   <%= form_for([@user, @user.opinions.build]) do |f| %>

    <p>
      <%= f.label :body, 'votre opinion' %><br>
      <%= f.text_area :body %>
    </p>
    <p>
       <%= f.submit %>
    </p>
   <% end %>

opinion_controller.rb

class OpinionsController < ApplicationController
  def create
    @user = current_user
    @opinion= @user.opinion.create(opinion_params)

  end

  private

  def opinion_params
     params.require(:opinion).permit(:body)
  end
end

在 books_controllers 这是我的显示方法:

 def show
   @user= current_user
   @books= Book.all
 end

我的路线:

get 'books/show' => 'books#show' ,如::books_list

resources :users do
  resources :opinions
end

我得到的错误:

nil:NilClass 的未定义方法 `opinions'

在这行代码中:

【问题讨论】:

    标签: has-many belongs-to ruby-on-rails-4.1


    【解决方案1】:

    很可能是您的表单中的@user.opinions 导致了这个问题。
    检查 current_user 是否返回对象。
    同样在您的创建方法中有错字(@user.opinion),它应该是@user.opinions。
    使用接受嵌套属性。

    【讨论】:

    • 感谢您的回复我在同一天解决了它只是一个零用户对象:)
    猜你喜欢
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 2015-11-16
    相关资源
    最近更新 更多