2

enter image description hereActionController :: UrlGenerationError в Приблизительные цены # новый

Я прочитал другие SO статьи, касающиеся UrlGenerationError-х, которые, кажется, указывают на сингуляризации или plurization слова, но я не думаю, что это вопрос здесь ,

Он работает, когда я удалить из нормированиям/_form.html.erb:

<%= render "comments/comments" %> 
<%= render "comments/form" %> 

Размесчение _form с :name & :tag_list, readd

<%= render "comments/comments" %> 
<%= render "comments/form" %> 

, а затем обновить. Какая сделка, когда нуль?

маршруты

resources :valuations do 
 
    resources :comments 
 
    end

comments_controller

class CommentsController < ApplicationController 
 
\t before_action :load_commentable 
 
    before_action :set_comment, only: [:show, :edit, :update, :destroy] 
 
    before_action :logged_in_user, only: [:create, :destroy] 
 

 
\t def index 
 
\t \t @comments = @commentable.comments 
 
\t end 
 

 
\t def new 
 
\t \t @comment = @commentable.comments.new 
 
\t end 
 

 
\t def create 
 
\t \t @comment = @commentable.comments.new(comment_params) 
 
\t \t if @comment.save 
 
\t \t \t @comment.create_activity :create, owner: current_user 
 
\t \t \t redirect_to @commentable, notice: "comment created." 
 
\t \t else 
 
\t \t \t render :new 
 
\t \t end 
 
\t end 
 

 
\t def edit 
 
\t \t @comment = current_user.comments.find(params[:id]) 
 
\t end 
 

 
\t def update 
 
\t \t @comment = current_user.comments.find(params[:id]) 
 
\t \t if @comment.update_attributes(comment_params) 
 
\t \t \t redirect_to @commentable, notice: "Comment was updated." 
 
\t \t else 
 
\t \t \t render :edit 
 
\t \t end 
 
\t end 
 

 
\t def destroy 
 
\t \t @comment = current_user.comments.find(params[:id]) 
 
\t \t @comment.destroy 
 
\t \t @comment.create_activity :destroy, owner: current_user 
 
\t \t redirect_to @commentable, notice: "comment destroyed." 
 
\t end 
 

 
private 
 
    def set_comment 
 
    @comment = Comment.find(params[:id]) 
 
    end 
 

 
\t def load_commentable 
 
\t \t resource, id = request.path.split('/')[1, 2] 
 
\t \t @commentable = resource.singularize.classify.constantize.find(id) 
 
\t end 
 

 
\t def comment_params 
 
\t \t params.require(:comment).permit(:content, :commentable) 
 
\t end 
 
end

valuations_controller

class ValuationsController < ApplicationController 
 
    before_action :set_valuation, only: [:show, :edit, :update, :destroy] 
 
    before_action :logged_in_user, only: [:create, :destroy] 
 

 
    def index 
 
    if params[:tag] 
 
     @valuations = Valuation.tagged_with(params[:tag]) 
 
    else 
 
     @valuations = Valuation.order('RANDOM()') 
 
    end 
 
    end 
 

 
    def show 
 
    @valuation = Valuation.find(params[:id]) 
 
    @commentable = @valuation 
 
    @comments = @commentable.comments 
 
    @comment = Comment.new 
 
    end 
 

 
    def new 
 
    @valuation = current_user.valuations.build 
 
    @commentable = @valuation 
 
    @comments = @commentable.comments 
 
    @comment = Comment.new 
 
    end 
 

 
    def edit 
 
    end 
 

 
    def create 
 
    @valuation = current_user.valuations.build(valuation_params) 
 
    if @valuation.save 
 
     redirect_to @valuation, notice: 'Value was successfully created' 
 
    else 
 
     @feed_items = [] 
 
     render 'pages/home' 
 
    end 
 
end 
 

 
    def update 
 
    if @valuation.update(valuation_params) 
 
     redirect_to @valuation, notice: 'Value was successfully updated' 
 
    else 
 
     render action: 'edit' 
 
    end 
 
end 
 

 
    def destroy 
 
    @valuation.destroy 
 
    redirect_to valuations_url 
 
    end 
 

 
private 
 
    def set_valuation 
 
     @valuation = Valuation.find(params[:id]) 
 
    end 
 

 
    def correct_user 
 
     @valuation = current_user.valuations.find_by(id: params[:id]) 
 
     redirect_to valuations_path, notice: "Not authorized to edit this valuation" if @valuation.nil? 
 
    end 
 

 
    def valuation_params 
 
     params.require(:valuation).permit(:name, :private_submit, :tag_list, :content, :commentable, :comment) 
 
    end 
 
end

комментарии/_form.html.erb

<%= form_for [@commentable, @comment] do |f| %> 
 
    <% if @comment.errors.any? %> 
 
    <div class="error_messages"> 
 
     <h2>Please correct the following errors.</h2> 
 
     <ul> 
 
     <% @comment.errors.full_messages.each do |msg| %> 
 
     <li><%= msg %></li> 
 
     <% end %> 
 
     </ul> 
 
    </div> 
 
    <% end %> 
 

 
<div class="america"> 
 

 
    <div class="form-group"> 
 
    <%= f.text_area :content, rows: 4, class: 'form-control', placeholder: 'Enter Comment' %> 
 
    </div> 
 

 
    <div class="america2"> 
 
    <%= button_tag(type: 'submit', class: "btn") do %> 
 
    <span class="glyphicon glyphicon-plus"></span> Comment 
 
    <% end %> 
 

 
</div> 
 

 
<% end %>

enter image description here

Большое вам спасибо за ваше время.

+0

Ваша фактическая статистика ошибок, что параметр valuation_id равен нулю. Вам нужно будет включить это, чтобы он знал, для какой оценки нужны комментарии. – patrick

+0

Hola @patrick! Где/как включить это? –

+0

До этого вы можете объяснить, как это происходит? Например, каковы шаги пользователя. Они пытаются добавить комментарий к оценке? – patrick

ответ

3

Если у вас есть вложенный ресурс, URL-адрес для создания комментария выглядит так: /valuations/123/comments где 123 - это идентификатор оценки - без идентификатора оценки этот URL-адрес не может быть сгенерирован.

На вашей оценке # новая страница оценка (то есть @commentable) является несохраненным объектом, поэтому у нее еще нет идентификатора, следовательно, ошибка в отсутствии valuation_id. Кроме того, наличие одной формы, вложенной в другую, является недопустимым html и приведет к нечетному поведению. С другой стороны, на вашей странице просмотра оценка имеет идентификатор, и поэтому все должно работать так, как есть.

Если вы хотите создать оценку и первоначальный комментарий (ы) в одном дыхании, то вы должны использовать accepts_nested_attributes_for и fields_for добавить поля для комментариев к вашей форме оценки (Есть и другие способы, но accepts_nested_attributes_for это то, что встроенный в рельсы)

+0

Ошибка уходит, но когда я нажимаю «Добавить комментарий», ничего не появляется. Нужно ли добавлять '_comments_fields.html.erb' и' _form_fields.html.erb' в папку комментариев или папку оценок? Я сделал оба, чтобы играть в это безопасно. Я также собираюсь сделать это для своих других представлений контроллеров, используя полиморфные комментарии, поэтому, если поля идут в каждом соответствующем представлении, это не будет много дублирования? Большое спасибо за помощь Фредерик! –

+0

@ Энтони, вы должны иметь возможность делиться комментариями с частичными, так как вы делитесь другими. Лучше всего открыть новый вопрос, чтобы обсудить вопрос «добавить комментарий» –

+0

Хорошая идея Фредерик. Вот раунд 2. http://stackoverflow.com/questions/29197689/how-to-show-polymorphic-comments-fields-partial-in-new. Я бы очень признателен за вашу помощь =] –

Смежные вопросы