Проблемы с публикацией комментария как 'current_user' (Devise) в микросообщении? - PullRequest
0 голосов
/ 29 января 2012

Так я публикую Микросообщение как current_user ( Devise ):

microposts_controller.rb:

 def create
    @user = current_user
    @micropost = @user.microposts.new(params[:micropost])
    @micropost.save
    redirect_to @micropost
  end

Вот так я размещаю комментарий в микросообщении:

comments_controller.rb:

  def create
    @micropost = Micropost.find(params[:micropost_id])
    @comment = @micropost.comments.create(params[:comment])
    redirect_to micropost_path(@micropost)
  end

Теперь я хотел бы оставить комментарий как current_user

Какие-либо предложения для достижения этой цели?

microposts / show.html.erb

<h2>Add a comment:</h2>
<%= form_for([@micropost, @micropost.comments.build]) do |f| %>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

EDIT:

Не уверен, если вам нужно это увидеть, но вот модели:

comment.rb:

class Comment < ActiveRecord::Base
  attr_accessible :content, :user_id

  belongs_to :micropost
  belongs_to :user
end

micropost.rb

class Micropost < ActiveRecord::Base
  attr_accessible :title, :content

  belongs_to :user
  has_many :comments
end

user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_many :microposts
  has_many :comments
end

1 Ответ

2 голосов
/ 29 января 2012

Попробуйте это в вашем comments_controller:

def create
  @micropost = Micropost.find(params[:micropost_id])
  comment_attr = params[:comment].merge :user_id => current_user.id
  @comment = @micropost.comments.create(comment_attr)
  redirect_to micropost_path(@micropost)
end

До сих пор, я думаю, к вашим комментариям не был прикреплен пользователь ..

Редактировать - я изменил: user будет: user_id. имеет больше смысла, так как у нас еще нет комментариев.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...