2013-01-31 165 views
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? 

評論控制研究ER:

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 

查看/評論/ _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] 

回答

1

你應該把你的屬性微博attr_accessible

attr_accessible :content, :micropost 

默認情況下,所有屬性都不可訪問。您必須在attr_accessible上定義您的可訪問屬性。

更多信息here

+0

因此,這意味着我應該刪除所有的attr_protected?此外,micropost不是微博模式的一部分。我添加了您的建議,但遇到了同樣的問題。 – Jaqx

+0

您能否介紹一下其他錯誤的更多細節? – JMarques

+0

我相信你必須在Micropost模型上有「attr_accessible:comment_id」。 – JMarques

0

JMarques具有正確的,但我喜歡用的attr_accessible_id以保持一致。考慮到這一點,你可以使用

# comment.rb 
attr_accessible :content, :micropost_id 

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

只是增加了一個try有以防萬一find_by_id回報nil

+0

嘗試是必要的 – Jaqx

0

根據rails4可以使用強大的參數:

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

    end 

    private 
    def micropost_params 
    params.require(:micropost).permit(:id) 
    end 
相關問題