0

我是编程新手,我正在努力解决我在我的应用程序中实现的新功能。我希望用户能够评论别人的微博。

我收到错误消息:无法批量分配微帖

用户模型:

attr_accessible :name, :email, :password, :password_confirmation #is this secure with password there?
attr_protected :admin   #attr_protected necessary?
has_many :microposts, dependent: :destroy
has_many :comments, :through => :microposts, dependent: :destroy

微贴模型:

attr_accessible :comment #basically the content of the post
attr_protected :user_id
has_many :comments, dependent: :destroy

评论型号:

attr_accessible :content, :micropost
belongs_to :user
belongs_to :micropost
validates :user_id, presence: true
validates :micropost_id, presence: true
validates :content, presence: true
default_scope order: 'comments.created_at ASC'   #is this necessary?

评论控制器:

def create
  @micropost = Micropost.find_by_id(params[:id])   #is this necessary?
  @comment = current_user.comments.create(:micropost => @micropost)
  redirect_to :back
end

用户控制器:

def show
  @user = User.find_by_id(params[:id])
  @microposts = @user.microposts.paginate(page: params[:page])
  @micropost  = current_user.microposts.build
  @comments = @micropost.comments
  @comment = current_user.comments.create(:micropost => @micropost) #build, new or create??
end

View/comments/_form:(这个部分在每个微博结束时调用)

<span class="content"><%= @comment.content %></span>
<span class="timestamp">Said <%= time_ago_in_words(@comment.created_at) %> ago.</span
<%= form_for(@comment) do |f| %>
  <%= f.text_field :content, placeholder: "Say Something..." if signed_in? %>
<% end %>

路线:

resources :users 
resources :microposts, only: [:create, :destroy] 
resources :comments, only: [:create, :destroy]
4

3 回答 3

1

你应该把你的属性 microposts 放在 attr_accessible

attr_accessible :content, :micropost

默认情况下,所有属性都是不可访问的。您必须在 attr_accessible 上定义您的可访问属性。

更多信息在这里

于 2013-01-31T12:11:51.507 回答
0

JMarques 是正确的,但我喜欢使用_idonattr_accessible来保持它的一致性。考虑到这一点,您可以使用

 # comment.rb
 attr_accessible :content, :micropost_id

 # controller
 current_user.comments.create(:micropost_id => @micropost.try(:id))

只是在那里添加了一个try以防万一find_by_id退货nil

于 2013-01-31T12:28:26.177 回答
0

根据 rails4 你可以使用强参数:

    def create
      @micropost = Micropost.find_by_id(micropost_params)
     ................

    end

   private
    def micropost_params
    params.require(:micropost).permit(:id)
    end
于 2014-05-07T08:05:13.223 回答