لا يمكن لجمعيات Rails (Selems_TO ، HAS_Many) حفظ معرفتين في الجدول باستخدام طريقة إنشاء (المستخدم ، النشر ، التعليق)

StackOverflow https://stackoverflow.com/questions/3732198

سؤال

في محاولة لكتابة تطبيق أساسي "يشبه المدونة" في Rails 3 ، أنا عالق مع الجمعيات. أحتاج إلى طريقة إنشاء حفظ post_id وكذلك user_id في جدول التعليق (الذي أحتاجه من أجل إعادة محاكمة جميع التعليقات التي كتبها المستخدم لعرضها)

يحتوي التطبيق على مستخدمين (المصادقة - ابتكر) ، منشورات (تم نشرها بواسطة المستخدمين - لكنني لست متأكدًا من أن الأمر مهم في حالتي) والتعليقات (على المنشورات ، التي نشرها المستخدمون).

يحتوي جدول التعليق على post_id ، الجسم ، وأيضًا user_id

ذات الصلة:

has_many :comments (In the Post model)
belongs_to :post (In the Comment model)
belongs_to :user (In the Comment model)
has_many :comments (In the User model)

الطرق:

resources :posts do
  resources :comments
end

resources :users do
  resources :comments
end

نموذج منشور التعليق المعروض في عرض المشاركات عرض: (المشاركات/show.html.erb)

<% form_for [@post, Comment.new] do |f| %>
  <%= f.label :body %>
  <%= f.text_area :body %>
  <%= f.submit %>
<% end %>

وأخيراً ، طريقة إنشاء في وحدة تحكم التعليقات:

أ) إذا كتبت هذا ، فسيتم كتابة post_id في قاعدة البيانات

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create!(params[:comment])
  redirect_to @post
end

ب) إذا كتبت هذا ، فسيتم كتابة user_id ...

def create
  @user = current_user
  @comment = @user.comments.create!(params[:comment])
  redirect_to @post
end

حاولت:

@comment = @post.comments.create!(params[:comment].merge(:user => current_user))

لكن هذا لا يعمل .. كيف يمكنني كتابة طريقة تحفظ user_id و post_id؟ هل كان علي أيضًا القيام ببعض التغيير في نموذج نشر التعليق (شيء مثل <٪ form_for [post ، @user ، comment.new] do | f | ٪>؟)

شكرًا لك!

هل كانت مفيدة؟

المحلول

لإعداد شيء مشابه جدًا ، استخدمت النموذج التالي:

<%= form_for [:place, @comment] do |f| %>
  #form fields here
<%= end %>

ثم في وحدة تحكم التعليقات:

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.build(params[:comment])
  @comment.user = User.find(current_user.id)

  respond_to do |format|
  if @comment.save
    format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
  else
    format.html { render :action => "new" }
  end
end

نهاية

يجب أن تبني الجمعيات بشكل صحيح! تمامًا جانباً ، هل تقصد أن تكون التعليقات متداخلة تحت: المستخدمون في طرقك؟ إذا كنت ترغب فقط في عرض جميع تعليقات المستخدم في صفحة الملف الشخصي ، فيمكنك القيام بشيء مثل:

<p>
  <b>Comments</b>
  <% if @user.comments.empty? %>
    No comments to display yet...
  <% else %>
    <% @user.comments.each do |comment| %>
      <p>
      <%= link_to "#{comment.post.title}", post_path(comment.post_id) %>, <%= comment.created_at %>
      <%= simple_format comment.content %>
      </p>
    <% end %>
  <% end %>
</p>

آمل أن بعض من أن يساعد!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top