【问题标题】:Rails3: How to insert a value to a column without user interaction?Rails3:如何在没有用户交互的情况下向列插入值?
【发布时间】:2010-10-17 15:22:02
【问题描述】:

我有帖子和用户模型,并且我有很多(帖子)到一个(用户)关联。 我只想显示该用户(当前用户)创建的帖子。 所以我必须以某种方式将当前登录的用户 id 注入“user_id”外键 在创建过程中的后期模型。我使用设计作为我的身份验证系统。 如何实现这一目标的任何解决方案? 我使用的是 Rails 3.0 版。

提前致谢。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 associations


    【解决方案1】:

    设计时只需使用“current_user”帮助器;)

    <% if user_signed_in? %> 
      <% current_user.posts.each do |post| %> 
        <%= post.title %>
      <% end %>
    <% end %>
    

    【讨论】:

    • 他还不能这样做,因为 Post 模型不知道是哪个用户制作的。
    【解决方案2】:

    在您的PostsController#create 方法中,您可以将Postuser 设置为current_user(因为您使用的是Devise)。

    def create
      @post = Post.create(params[:post]) do |p|
        p.user = current_user
      end
      #respond_with(@post) or Rails 2 equivalent
    end
    

    【讨论】:

      猜你喜欢
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多