简体   繁体   English

在Rails中创建关联

[英]Create association in Rails

I've got model Project and model User. 我有模型项目和模型用户。 I've got belongs_and_has_many in these. 我在其中有belongs_and_has_many。 But now I need to tell Rails: this specific user belongs to this specific project. 但是现在我需要告诉Rails:这个特定的用户属于这个特定的项目。 How can I do it in Project controller, and how can I call this method from project view? 如何在Project Controller中执行此操作,如何从Project视图中调用此方法? Thank you very much. 非常感谢你。

in project's* show.html.erb * I ve got: 在项目的* show.html.erb中 *我有:

<select id="user_select" name="user_select" class="input-large">
  <% @users.each do |user| %>
    <option><%= user.username %></options>
  <% end %>
</select>
<!-- button to addfriend method here -->

And I need to call method "addfriend" from here with parameter from selection to associated project with this user :-/ 我需要从此处使用该用户从选择到关联项目的参数中调用方法“ addfriend”:-/

Method addfiend in project controller: 项目控制器中的方法addfiend

def addfriend
      @project = Project.find(params[:id])
      @project.users << User.find(params[:user])
      respond_to do |format|
        format.html { redirect_to project, :notice => 'Added.' }
      end
end

如果在模型项目中,您具有has_and_belongs_to_many :users ,则您的项目对象具有隐式collection用户,可以像其他任何collection一样将其添加,例如:

project.users << User.find(:first, :conditions => "name = 'foo'")

This would look something like that in your controller action: 这在您的控制器操作中看起来像这样:

@project = Project.create(:user_id => user_id)

while user_id is your foreign key (something you would probably want to pass from your view). 而user_id是您的外键(您可能希望从视图中传递的内容)。

This code will be written in some controller action, and you would have to define a route for connecting a URL to this action. 该代码将在某些控制器操作中编写,并且您必须定义将URL连接到此操作的路由。

Notice that once you call the action that runs this code you can access @project from your view. 请注意,一旦调用了运行此代码的操作,便可以从视图中访问@project。

You can read about routes here . 您可以在此处阅读有关路线的信息 You can read about mvc in rails here . 您可以在此处阅读有关rails中的mvc的信息 You can read about associations here: http://guides.rubyonrails.org/association_basics.html 您可以在此处阅读有关关联的信息: http : //guides.rubyonrails.org/association_basics.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM